Lately I was working on a problem where I had to toggle something in React JS and I couldn't find a simple 1-2 liner solution for that, like we have in Jquery. If you have ever used it, you probably know what I am talking about.
Note: I am not trying to compare
Jquery
andReact
here. They both serve their purpose very well.
Let's take an example. We will create a button that changes the text from Off
to On
and vice-versa with one click of a button.
Let's talk through this example step by step:
- Create a button - we will use material-UI for that.
- Create a state that will hold the
On/Off
value. - Show
On/Off
text once user clicks the button. - If the text says
On
and user clicks the button, it should change the text toOff
and vice-versa.
- Step 1: Create a button
<Button variant="contained" color="primary">
Toggle
</Button>
-
Step 2: Create a state that will hold value
On/Off
:
const [textState, setTextState] = useState("off");
We are taking Off
as initial state to avoid any kind of code smell.
-
Step 3: Show
On/Off
text on click of the button.
This part involves two small but important steps:
- A text that changes with the click of the button
- A function to handle the toggle when user clicks on the button
So, let's pass the text first, buttonState
will give us Off
by default as it is our initial state:
<h3>{textState}</h3>
Add the Handler function:
const toggleText = () => {
setTextState((state) => (state === "On" ? "Off" : "On"));
};
We are updating the state of the button here. If it is On
, change it to Off
and if it is Off
, change it to On
.
-
Step 4: Toggle, to achieve this we only need to pass our handler function to the
onClick
of<Button>
from step 1. Like this:
<Button variant="contained" color="primary" onClick={toggleText}>
Toggle
</Button>
And that's all! Here is how it looks when we put all the above code together:
Top comments (2)
Very well sussed out 🙂. If I could suggest a one things that might make things easier for you.
As we're dealing with a toggle rather than storing you text in a state you could store a Boolean. Doing this make our inverting logic a lot simpler it also means we can do other things with with the state (like change the button colour).
thank you for the suggestion. You are right, we can do that.
When I decided to write this blog, my main motive was to only focus on one functionality and explain end to end process of solving the problem, I would agree, if anyone if looking for more flexibility in their code base, your advice is very useful.