React Tutorials
React ES6
React Hooks
In React, you can assign parts in terms.
There are several ways to do this.
if
StatementsWe can use the if
JavaScript operator to determine which component we will provide.
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/>;
}
ReactDOM.render(
<Goal isGoal={false} />,
document.getElementById('root')
);
Try changing the isGoal
attribute to true
:
ReactDOM.render(
<Goal isGoal={true} />,
document.getElementById('root')
);
&&
OperatorAnother way to conditionally provide part of React is to use &&
operators.
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'];
ReactDOM.render(
<Garage cars={cars} />,
document.getElementById('root')
);
If cars.length
equals truth, the saying && will do.
Try removing the cars
array:
const cars = [];
ReactDOM.render(
<Garage cars={cars} />,
document.getElementById('root')
);
Another way to give things conditionally is to use a ternary operator.
condition ? true : false
We will return to the scoring model.
Return the MadeGoal
component if isGoal
is true
, otherwise return the MissedGoal
component:
function Goal(props) {
const isGoal = props.isGoal;
return (
<>
{ isGoal ? <MadeGoal/> : <MissedGoal/> }
</>
);
}
ReactDOM.render(
<Goal isGoal={false} />,
document.getElementById('root')
);