DEV Community

Cover image for Day 5: Conditional Rendering and Lists in React
Dipak Ahirav
Dipak Ahirav

Posted on

Day 5: Conditional Rendering and Lists in React

Welcome to Day 5 of our React.js learning journey! Today, we'll explore how to implement conditional rendering and work with lists in React. These concepts are essential for building dynamic and interactive user interfaces.

Conditional Rendering in React

Conditional rendering allows you to show or hide components based on certain conditions. In React, you can achieve conditional rendering using JavaScript expressions within JSX. Let's look at an example:

function Greeting({ isLoggedIn }) {
  return isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>;
}

function App() {
  const isLoggedIn = true;

  return (
    <div>
      <Greeting isLoggedIn={isLoggedIn} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the Greeting component renders a different message based on the value of isLoggedIn. If isLoggedIn is true, it displays "Welcome back!", otherwise it shows "Please log in."

Rendering Lists in React

Lists are a common feature in web applications, and React provides a simple way to render lists of elements dynamically. You can use the map method to iterate over an array and render components for each item. Here's an example:

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

function App() {
  const todos = [
    { id: 1, text: 'Learn React' },
    { id: 2, text: 'Build a project' },
    { id: 3, text: 'Deploy to production' }
  ];

  return (
    <div>
      <h2>My Todo List</h2>
      <TodoList todos={todos} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the TodoList component receives an array of todos and uses the map method to render a list of todo items dynamically.

Conclusion

Today, you've learned how to implement conditional rendering and work with lists in React. Conditional rendering allows you to show or hide components based on conditions, while rendering lists dynamically enables you to display collections of elements efficiently.

By mastering these concepts, you can create more interactive and engaging user interfaces in your React applications. Stay tuned for Day 6, where we'll explore more advanced topics in React development.


I hope this blog post has provided you with a clear understanding of how to implement conditional rendering and work with lists in React. Feel free to experiment with these concepts in your own projects to solidify your knowledge. Good luck with your React.js learning journey!

Top comments (1)

Collapse
 
dipakahirav profile image
Dipak Ahirav

Next part -> Day - 6