In React, you can create distinct components that encapsulate the behavior you need. Then, you can render only some of them, depending on the state of your application.
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.
Let's explore some examples to see how conditional rendering works in React, we will start with a new React App so if you are just beginning with React i recommend you check out my blog on creating your first React Application here or clone the starter template on my Github:
To create a new App open the terminal and issue this command :
npx create-react-app demo-app
This will generate a new react project for us so we can change the directory to the new project and start the server to make sure our app is up and running correctly.
cd demo-app
Now let's start the development server with some built-in commands:
Using npm :
npm start
Or yarn :
yarn start
Then open localhost:3000 in your browser to see the app.
You should see something like this :
In your browser. If you made it to this point congrats!! now are going to dive into how conditional rendering works in react. First of all, if we open the project in our text editor, we can see that it contains an src folder that holds all the files you will use to write your application. The public folder contains assets like logos, HTML, icons and all the stuff you will need to build the application.
So let's create a new directory component inside the **src ** folder that will contain all the components:
cd src && mkdir components
This will create a new directory in the src folder, now let's create the file so we can write the logic inside
cd components && touch pages.js
This will create the **pages.js ** file in the components directory, let's open it and paste this code :
export const PrivateComponent=()=> {
return(
<h1>Only authorized users can see this!!!!!</h1>
)
};
export const RegularComponent=()=> {
return(
<h1>Everyone can see this!!!!!</h1>
)
};
Now let's open the App.js file inside the src folder and import these components so we can display them, first we will make a few changes to it by omitting a few things from the app that we don't need making the final file look like this:
import { PrivateComponent, RegularComponent } from "./components/pages";
import "./App.css";
function App(props) {
if (props.isAuthenticated) {
return (
<div className="App">
<PrivateComponent />
</div>
);
} else if (!props.isAuthenticated) {
return (
<div className="App">
<RegularComponent />
</div>
);
};
};
export default App;
Since the isAuthenticated prop is not available yet to the app even when we start the server and go to localhost:3000 we will see a blank page, so let's open the index.js file inside src and add this code to the App component:
isAuthenticated={false}
Your index.js file should look like this :
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App isAuthenticated={false}/>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Now when you restart the server and go to localhost:3000 you should see
What happened? since the current state is set to false that is why we are seeing the regular component but when we change it to true:
isAuthenticated={true}
You will see
Great!!!! we have successfully rendered elements based on the current state of the component, we can even use the Javascript **Ternary operator ** to determine the current state of the app and render base on that, for this, we have to refactor our App.js code to this :
import { PrivateComponent, RegularComponent } from "./components/pages";
import "./App.css";
function App(props) {
return (
<>
{props.isAuthenticated ?<div className="App"><PrivateComponent/> </div>: <div className="App"><RegularComponent/> </div>}
</>
);
};
export default App;
Which will work the same way depending on the state of the App, either true or **false **.
CONGRATULATIONS💯🎉
Now you should have a solid understanding of how we use conditionals to determine the state of react apps, you have also had a peak of react functional components and thanks a lot for making it through! I hope this helps someone out there!