Home >Web Front-end >JS Tutorial >Conditional Rendering in React
Conditional rendering in React allows you to render different components or elements based on certain conditions, such as state or props. Here are some common methods to achieve conditional rendering:
You can use standard JavaScript if-else statements inside your component.
function MyComponent({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } else { return <h1>Please sign in.</h1>; } }
This is a concise way to render content based on a condition.
function MyComponent({ isLoggedIn }) { return ( <h1> {isLoggedIn ? 'Welcome back!' : 'Please sign in.'} </h1> ); }
You can use the logical AND operator to render a component only if a condition is true.
function MyComponent({ isLoggedIn }) { return ( <div> {isLoggedIn && <h1>Welcome back!</h1>} {!isLoggedIn && <h1>Please sign in.</h1>} </div> ); }
For more complex conditions, you can use a switch statement.
function MyComponent({ status }) { switch (status) { case 'loading': return <h1>Loading...</h1>; case 'success': return <h1>Data loaded successfully!</h1>; case 'error': return <h1>There was an error!</h1>; default: return null; } }
Here’s a full example using functional components:
import React from 'react'; function App() { const [isLoggedIn, setIsLoggedIn] = React.useState(false); return ( <div> <button onClick={() => setIsLoggedIn(!isLoggedIn)}> {isLoggedIn ? 'Logout' : 'Login'} </button> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); } export default App;
Choose the method that best suits your needs based on the complexity of your conditions and your personal coding style. Let me know if you need more examples or explanations!
The above is the detailed content of Conditional Rendering in React. For more information, please follow other related articles on the PHP Chinese website!