Hello ReactJS Friends,
In today’s blog, you will get an idea about Conditional Rendering in ReactJS.
Contents
In react, you can redesign components based on your condition.
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like “if” or conditional operators like “&&” and “? :” to create elements representing the current state, and let React update the UI to match them.
function CompleteTask(props) { return <h1>Completed.</h1>; } function NotCompleteTask(props) { return <h1>Not Completed.</h1>; }
There are several ways to conditionally render components in ReactJS.
We can create components that display whether tasks are completed or not.
function CheckTaskProgress(props) { const isTaskComplete = props.isTaskComplete; if (isTaskComplete) { return <CompleteTask />; } return <NotCompleteTask />; } const root = ReactDOM.createRoot(document.getElementById('root')); // Try changing to isLoggedIn={true}: root.render(<CheckTaskProgress isTaskComplete ={false} />);
This includes the javascript logical && operator. It can be handy for conditionally including an element
function Mailbox(props) { const unreadMessages = props.unreadMessages; return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div> ); } const messages = ['React', 'Re: React', 'Re:Re: React']; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Mailbox unreadMessages={messages} />);
Another method for conditionally rendering elements inline is to use the JavaScript conditional operator condition ? true : false.
In the example below, we use it to conditionally render a small block of text.
render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in. </div> ); }
Hope you got a precise understanding of ReactJS Conditional Rendering. If you have any doubts, let me know through the comment box. Share the article with your friends, and stay in touch with us for more ReactJS tutorials.
Happy Coding!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…