One way to dynamically or conditionally add (or toggle) a class to an element inside of a React document is using the useState hook.
In this example I will show you how to show/hide an element by clicking a button. In order to do that I'm going to create a function that will toggle a class on the affected element.
First let's create a state inside of a React component.
export default function OurComponent() {
const [button, setButton] = useState(false)
return (
<section> </section>
)
}
Now let's create a button and a paragraph that initially will not be visible.
export default function OurComponent() {
const [button, setButton] = useState(false)
return (
<section>
<button>Show Paragraph</button>
<p className="hidden">This is our paragraph.</p>
</section>
)
}
In a .css file:
.hidden {
display: none;
}
.show {
display: block;
}
Now let's add an onClick function to our button.
export default function OurComponent() {
const [button, setButton] = useState(false)
const showParagraph = () => {
...
}
return (
<section>
<button onClick={showParagraph}>Show Paragraph</button>
<p className="hidden">This is our paragraph.</p>
</section>
)
}
In the next step I will create a variable that will be responsivle for checking the state of button. If the state is true we will asign a value with the same name as our class with the display property of block.
let checkState = button ? 'show' : ''
Next step: let's toggle the state of button (toggle between true/false) inside of our onClick function.
let checkState = button ? 'show' : ''
const showParagraph = () => {
setButton(!button)
}
This is a good moment to console.log the checkState variable. If we did everything right, every other time we click the button, the console should print show.
Now, there's only one thing left to do. We need to add our variable checkState as a class on the p element.
<p className={`hidden ${checkState}`}>This is our paragraph.</p>
Our paragraph is hidden by default, as hidden class has the display property set to none. When we click the button, the paragraph gets another class of
Comments (0)
Be the first to leave a comment