Here you can find 4 different strategies to conditionally render elements and components in React.
Using the && operator
The && operator can be used to render an element only when a condition is truthy. In this example, the paragraph <p>Loading...</p> is rendered only when the isLoading state is true.
import React, { useState } from 'react';
export default function MyComponent() {
const [isLoading, setIsLoading] = useState(false);
const handleClick = () => {
setIsLoading(true);
};
return (
<div>
<button onClick={handleClick}>Start loading</button>
{isLoading && <p>Loading...</p>}
</div>
);
}
Early return
You can use an if statement to return early from the component if a condition is met. After clicking the button in this example, isLoading is set to true , and the component returns the paragraph <p>Loading...</p>, effectively replacing the button.
import React, { useState } from 'react';
export default function MyComponent() {
const [isLoading, setIsLoading] = useState(false);
const handleClick = () => {
setIsLoading(true);
};
if (isLoading) {
return <p>Loading...</p>;
}
return <button onClick={handleClick}>Start loading</button>;
}
If you don't want your component to render anything when a condition is met, you can simply return null.
import React, { useState } from 'react';
export default function MyComponent() {
const [isLoading, setIsLoading] = useState(false);
const handleClick = () => {
setIsLoading(true);
};
if (isLoading) {
return null;
}
return <button onClick={handleClick}>Start loading</button>;
}
Ternary operator
The ternary operator is another useful technique for conditional rendering. In this example, if isLoading is true, the paragraph <p>Loading...</p> is rendered; otherwise, the button is rendered.
import React, { useState } from 'react';
export default function MyComponent() {
const [isLoading, setIsLoading] = useState(false);
const handleClick = () => {
setIsLoading(true);
};
return isLoading ? <p>Loading...</p> : <button onClick={handleClick}>Start loading</button>;
}
You can also use the ternary operator to conditionally render strings within JSX. In the example below, the paragraph content changes based on the isLoading state.
import React, { useState } from 'react';
export default function MyComponent() {
const [isLoading, setIsLoading] = useState(false);
const handleClick = () => {
setIsLoading(true);
};
return (
<div>
<button onClick={handleClick}>Start loading</button>
<p>The component is {isLoading ? 'currently' : 'not'} loading.</p>
</div>
);
}
Using variables to store elements
Another method for conditional rendering is to assign elements to a variable and conditionally update that variable. Although less common, this approach is also a valid way to selectively render elements in React.
import React from 'react';
export default function MyComponent(props) {
let content = <p>Loading...</p>;
if (!props.isLoading) {
content = <h1>Welcome back!</h1>;
}
return content;
}