This article is sponsored by Fiverr - Freelance to get extra income or become a full-time freelancer.
The state was managed by adding an event listener to detect fired events in previous articles. This article will go even further to render components conditionally. The ternary operator, ?
symbol in the ternary expression will be used to check if a condition is true or not, instead of the if-else statement.
Below are the existing code snippets to illustrate in this article:
index.css
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
padding: 0;
margin: 0;
}
body {
background-color: #f0f0f0;
}
Person/Person.css
.Person {
margin: 20px auto;
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
line-height: 1.7;
width: 12.375rem;
font-family: 'Roboto', sans-serif;
background-color: white;
}
.Person-Card {
display: inline-flex;
margin: 5px;
}
.Person-Container {
padding: 5px 20px;
border: 1px solid #999;
}
body.module.css
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
button {
border: 1px solid #000;
border-radius: 4px;
background-color: blueviolet;
color: white;
margin: 20px auto;
padding: 10px;
cursor: pointer
}
.btns {
display: flex;
}
App.js
import React from 'react';
import { useState } from 'react';
import Person from './Person/Person';
import bodyStyles from './body.module.css';
const App = () => {
const [state, setState] = useState({
persons: [
{ name: 'Bello', language: 'React', id: '2sdr3' },
{ name: 'Michael', language: 'Vue', id: 'de6c3' },
{ name: 'Mary', language: 'Angular', id: 'c1z3x' }
],
showPersons: true
});
const personsToggleHandler = () => {
setState((prevState) => ({
...prevState,
// code here
}))
}
return (
<div className={bodyStyles.body}>
<div className='Person-Container'>
<Person
name={state.persons[0].name}
language={state.persons[0].language}
id={state.persons[0].id} />
<Person
name={state.persons[1].name}
language={state.persons[1].language}
id={state.persons[1].id} />
<Person
name={state.persons[2].name}
language={state.persons[2].language}
id={state.persons[2].id} />
<h3 style={{ textAlign: 'center', fontFamily: 'sans-serif' }}>Toggle Persons</h3>
</div>
<div className={bodyStyles.btns}>
<button
className={bodyStyles.button}
onClick={personsToggleHandler}>Toggle Person Cards</button>
</div>
</div>
);
};
export default App;
The 3 Person components, <Person />
are the list that can be toggled conditionally.
Below are the steps to toggle components in React (App.js).
Steps
For components to be toggled successfully, they need to be wrapped in a parent element.
- Wrap the 3
<Person />
components in adiv
<div>
<Person
name={state.persons[0].name}
language={state.persons[0].language}
id={state.persons[0].id} />
<Person
name={state.persons[1].name}
language={state.persons[1].language}
id={state.persons[1].id} />
<Person
name={state.persons[2].name}
language={state.persons[2].language}
id={state.persons[2].id} />
</div>
- Place a curly bracket around it.
{
<div>
<Person
name={state.persons[0].name}
language={state.persons[0].language}
id={state.persons[0].id} />
<Person
name={state.persons[1].name}
language={state.persons[1].language}
id={state.persons[1].id} />
<Person
name={state.persons[2].name}
language={state.persons[2].language}
id={state.persons[2].id} />
</div>
}
- Let's assume the expression in the curly bracket refers to a variable,
personList
. Assign the<Person />
components to thepersonList
variable before thereturn
keyword.
const personList = { <div>...</div> }
- The ternary operator, the
?
symbol checks if a condition is true or false. That is ifpersonList
is true, open the Person's components; else close if false.
const showPersons ? true : false;
// where personList = true
- Since show person is true, we need a function to close it and open it again...
const personsToggleHandler = () => {
const showCards = state.showPersons;
setState((prevState) => ({
...prevState,
showPersons: !showCards
}))
}
- Since hooks do not merge, the state needs to be spread on it. Do this in a function,
personsToggleHandler
. Also always reverse the condition when an event is fired open a click.
const personsToggleHandler = () => {
const showCards = state.showPersons;
setState((prevState) => ({
...prevState,
showPersons: !showCards
}))
}
Below is the needed result:
import React from 'react';
import { useState } from 'react';
import Person from './Person/Person';
import bodyStyles from './body.module.css';
const App = () => {
const [state, setState] = useState({
persons: [
{ name: 'Bello', language: 'React', id: '2sdr3' },
{ name: 'Michael', language: 'Vue', id: 'de6c3' },
{ name: 'Mary', language: 'Angular', id: 'c1z3x' }
],
showPersons: true
});
const personsToggleHandler = () => {
const showCards = state.showPersons;
setState((prevState) => ({
...prevState,
showPersons: !showCards
}))
}
return (
<div className={bodyStyles.body}>
<div className='Person-Container'>
{
state.showPersons ?
<div>
<Person
name={state.persons[0].name}
language={state.persons[0].language}
id={state.persons[0].id} />
<Person
name={state.persons[1].name}
language={state.persons[1].language}
id={state.persons[1].id} />
<Person
name={state.persons[2].name}
language={state.persons[2].language}
id={state.persons[2].id} />
</div> : false
}
<h3
style={{
textAlign: 'center',
fontFamily: 'sans-serif'
}}>Toggle Persons</h3>
</div>
<div className={bodyStyles.btns}>
<button
className={bodyStyles.button}
onClick={personsToggleHandler}>Toggle Person Cards</button>
</div>
</div>
);
};
export default App;
A falsy statement can either be
false
,null
,''
, orundefined
. Althoughfalse
is used above, we will change it tonull
in the next example. This is generally true in vanilla JavaScript or in any other programming language.
Since the Person's components is named, personList
, the above code can be re-written as shown below:
import React from 'react';
import { useState } from 'react';
import Person from './Person/Person';
import bodyStyles from './body.module.css';
const App = () => {
const [state, setState] = useState({
persons: [
{ name: 'Bello', language: 'React', id: '2sdr3' },
{ name: 'Michael', language: 'Vue', id: 'de6c3' },
{ name: 'Mary', language: 'Angular', id: 'c1z3x' }
],
showPersons: true
});
const personsToggleHandler = () => {
const showCards = state.showPersons;
setState((prevState) => ({
...prevState,
showPersons: !showCards
}))
}
const personsList = (
<div>
<Person
name={state.persons[0].name}
language={state.persons[0].language}
id={state.persons[0].id} />
<Person
name={state.persons[1].name}
language={state.persons[1].language}
id={state.persons[1].id} />
<Person
name={state.persons[2].name}
language={state.persons[2].language}
id={state.persons[2].id} />
</div>
);
return (
<div className={bodyStyles.body}>
<div className='Person-Container'>
{
state.showPersons ? personsList : null
}
<h3
style={{
textAlign: 'center',
fontFamily: 'sans-serif'
}}>Toggle Persons</h3>
</div>
<div className={bodyStyles.btns}>
<button
className={bodyStyles.button}
onClick={personsToggleHandler}>Toggle Person Cards</button>
</div>
</div>
);
};
export default App;
Happy Coding!!!
Techstack | Fiverr
Techstack article, sponsored by Fiverr.
- Connect to freelancers with proven business experience.
- Get matched with the perfect talent by a customer service manager.
- Freelance to get extra income or become a full-time freelancer.
Sign up to find the perfect freelance services for your business or become a freelancer.
Support what I do and push me to keep making free content.
Top comments (0)