Sometimes, we want to show or hide elements or components with React.
In this article, we’ll look at how to show or hide elements or components with React.
Show or Hide Elements or Components in React
We can show or hide elements or components in React with the ternary operator.
For instance, we can write:
import React, { useState } from "react";
const Results = () => <div>Some Results</div>;
export default function App() {
const [showResults, setShowResults] = useState(false);
const onClick = () => setShowResults(true);
return (
<div>
<input type="submit" value="Search" onClick={onClick} />
{showResults ? <Results /> : null}
</div>
);
}
We have the Results component which we want to show after we click the Search button.
When we click the button, we run the onClick function which calls setShowResults with true to set showResults to true .
If showResults is true , then the Results component is rendered.
Otherwise, null , which is nothing, is rendered.
We can do the same thing with HTML elements.
Conclusion
We can show or hide elements or components in React with the ternary operator.