React - Conditional Rendering of Elements, CSS Classes

Hello There! We have seen already how we can render components, apply and render CSS for components  and even render component collection or lists

In real time applications, states or props will hold values and based on them, we might need to  add/remove components, show or hide elements or apply CSS classes.

Will take an example of library of Books.

  • Use case 1 - Conditional Show/Hide Elements
    • If books.length > 0, we will show them otherwise we will show message stating that there are no books available. 
  • Use case 2 - Conditional Add/Remove CSS classes dynamically
    • If a books are available but we want to decide on runtime to promote or highlight a specific book based on a book' s property say special. Meaning highlight book title if special flag is true.

Lets look at each use case in detail.

Use case 1 - Conditional Show/Hide Elements

  • To begin with, lets set our books collection as empty.
  • As seen while rendering component collection earlier, we will use inline method for rending the books.


   class BookLibrary extends React.Component {
    render() {
        const books = [
       
        ];

        return (
        <>
            <section className="booklist">
            {/* Check if books are available using ternary operator provided by JavaScript */}
            {books.length > 0 ? (
                // if present, return component collection
                books.map((book) => (
                <Book key={book.id} book={book} /> //arrow function, implicit return
                ))
            ) : (
                //if books are not present, show a message
                <h2>Sorry, currently we have no books in our library.</h2>
            )}
            </section>
        </>
        );
    }
    }

    ReactDOM.render(<BookLibrary />, document.getElementById("container"));

  • As you can see above, you can check and render book collection if its available or not otherwise gracefully can handle such situations by displaying appropriate message on the browser.

Use Case 2 - Add/Remove CSS classes dynamically

  • In use case 2, we have books in our collection. But there could be books which do not have description available with them. 
  • In that case we dont want to show such books similar to use case 1, but instead of returning or showing some message, we will hide the <p> element of description completely from the DOM. 
  • So, in our books collection, we have 3 books out of which book #3 doesn't have description. 
  • We have added a new CSS class to hide an element, refer it below:

    • CSS class to highlight a special book

    •   /* css class for special books */
        .special {
          background-color: tomato;
        }


    • Class with books, conditional CSS class

    • const books = [
              {
                  id: 1,
                  title: "Life's Amazing Secrets",
                  author: "Gaur Gopal Das",
                  coverImage: "./images/lifes-amazing-secrets.jpg",
                  description:
                  "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga, corporis!",
              },
              {
                  id: 2,
                  title: "The Alchemist",
                  author: "Paulo Cohlo",
                  coverImage: "./images/the-alchemist.jpg",
                  description:
                  "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga, corporis!",
              },
              {
                  id: 3,
                  title: "Grandma's Bag of Stories",
                  author: "Sudha Murthy",
                  coverImage: "./images/grandmas-bag-of-stories.jpg",
                  description:
                  "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Fuga, corporis!",
              // notice that we have added a flag called as special only for this object
              special: true,
              },
            ];

           

        class BookAuthor extends React.Component {
          render() {
            const { title, author, description, special } = this.props;
            return (
              <>
                <section>
                  {/* Append special class to existing class list if special flag is true */}
                  <h1 className={special ? "book-title special" : "book-title"}>
                    {title}
                  </h1>
                  <h4 className="book-author">{author}</h4>
                  <p className="description">{description}</p>
                  <button className="btn" onClick={this.props.buyBook}>
                    Buy this Book!
                  </button>
                </section>
              </>
            );
          }
        }


    • Response in browser:
    • Image when special class is applied

Please note that we can use any operator instead of ternary operator while performing conditional rendering. We can club this method to render component collections, components, elements etc.



Comments

Popular Posts