Prevent Component from Rendering in ReactJS
Today we will show you how to prevent component from rendering in ReactJS. When you want to prevent the component from rendering based on some condition then you can simply return the `null` value.
Prevent Component from Rendering in ReactJS, How to prevent a rerender in React JS, Avoiding Unnecessary Renders in React, react prevent child component from rendering, react functional component prevent re-render, prevent rerender react hooks.
Checkout more articles on ReactJS
- If Else Statement in ReactJS
- Element Variables in ReactJS
- Image zoom in ReactJS
- Form Validation in ReactJS
- URL Parameters with React Router
Example of Prevent Component from Rendering
Let’s take an example where we will use toggle button to show hide the tab based on the button click.
First, create functional component to render the tab content. Here we will prevent component from rendering based on the condition.
Tab.js
import React from 'react';
const tab = (showTab) => {
// prevent component from rendering
if (!showTab) {
return null;
}
return <div style={{ marginTop: 10 }}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
}
export default tab;
Now it’s time to call the tab component from the parent component and pass the toggle flag so based on it we can prevent component.
App.js
import React, { useState } from 'react';
import tab from './Tab';
const App = () => {
const [showTab, setShowTab] = useState(true);
// handle click event of the toggle button
const handleToggle = () => {
setShowTab(preState => !preState);
}
return (
<div className="App">
<div style={{ marginBottom: 10 }}><a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></div>
<input type="button" value="Toggle Tab" onClick={handleToggle}></input>
{tab(showTab)}
</div>
);
}
export default App;
Output:
Output - Prevent Component from Rendering in ReactJS - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding!