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) { returnWelcome back!
; } else { returnPlease sign in.
; } }
This is a concise way to render content based on a condition.
function MyComponent({ isLoggedIn }) { return ({isLoggedIn ? 'Welcome back!' : 'Please sign in.'}
); }
You can use the logical AND operator to render a component only if a condition is true.
function MyComponent({ isLoggedIn }) { return ({isLoggedIn &&); }Welcome back!
} {!isLoggedIn &&Please sign in.
}
For more complex conditions, you can use a switch statement.
function MyComponent({ status }) { switch (status) { case 'loading': returnLoading...
; case 'success': returnData loaded successfully!
; case 'error': returnThere was an error!
; default: return null; } }
Here’s a full example using functional components:
import React from 'react'; function App() { const [isLoggedIn, setIsLoggedIn] = React.useState(false); return ({isLoggedIn ?); } export default App;Welcome back!
:Please sign in.
}
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!
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3