HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
In React, you can conditionally render components.There are several ways to do this
We can use the if
JavaScript operator to decide which component to render.
We'll use these two components:
function MissedGoal() {
return <h1>MISSED!</h1>;
}
function MadeGoal() {
return <h1>Goal!</h1>;
}
Now, we'll create another component that chooses which component to render based on a condition:
function Goal(props) {
const isGoal = props.isGoal;
if (isGoal) {
return <MadeGoal/>;
}
return <MissedGoal/>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);
Try changing the isGoal
attribute to true
:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={true} />);
Another way to conditionally render a React component is by using the &&
operator.
We can embed JavaScript expressions in JSX by using curly braces:
function Garage(props) {
const cars = props.cars;
return (
<>
<h1>Garage</h1>
{cars.length > 0 &&
<h2>
You have {cars.length} cars in your garage.
</h2>
}
</>
);
}
const cars = ['Ford', 'BMW', 'Audi'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);
If cars.length
is equates to true,
the expression after &&
will render.
Try emptying the cars
array:
const cars = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);
Another way to conditionally render elements is by using a ternary operator.
condition ? true : false
We will go back to the goal example.
Return the MadeGoal
component if
isGoal
is true
,
otherwise return the MissedGoal
component:
function Goal(props) {
const isGoal = props.isGoal;
return (
<>
{ isGoal ? <MadeGoal/> : <MissedGoal/> }
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);
To learn more, see the ternary operator section.
Use the correct logical operator to complete the following component.
function App({isLoggedIn}) {
return (
<>
<h1>My Application</h1>
{isLoggedIn <Profile /> }
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);