ReactJS vs Javascript vs JQuery
Here is the javascript:See the Pen Toggle hide class name using vanilla javascript by Noobie Programmer (@noobieprogrammer) on CodePen.
Here is the jquery:
See the Pen bGpMyyp by Noobie Programmer (@noobieprogrammer) on CodePen.
And, most especially using ReactJS:
See the Pen ReactJS: create a toggle in less than 30 seconds by Noobie Programmer (@noobieprogrammer) on CodePen.
Code
So since my favorite is react let's break down the code one by one. And then
later on you'll realize it is so easy to create a toggle or use any condition
with react.
Of course before anything else we need a react template
where all the basic imports are already available to use. Since I'll be using
codepen here's my template just in case you want to create a react
pen: https://codepen.io/noobieprogrammer/pen/VwaRrJb
First we add a button:
ReactJS Button | Noobie Programmer |
but nothing is happening right? so let's add a state variable named show. What we want is to toggle it from true to false and vice versa everytime we click the button. So first let's initialize it to false in the constructor since we want the div to be hidden first once the page is loaded:
React constructor - initialized show to false | Noobie Programmer |
Then let's create a toggle method who will toggle the show variable everytime the function is called:
Toggle method | Noobie Programmer |
Let's pass it on the onClick property of the button. Also, let's change the text of the button so that it changes depending on the state of the show variable:
Passing the onclick method | Noobie Programmer |
And one last thing is to add an if else condition on the div using the ternary operator. Show it if the show variable is true otherwise return null or basically nothing.
And we are done! and here's the final code:
See the Pen ReactJS: create a toggle in less than 30 seconds by Noobie Programmer (@noobieprogrammer) on CodePen.
Conclusion
As what you can see from the code above, it is easy to create a ReactJS toggle hide/show when compared to vanilla javascript. It's almost as easy as in JQuery.The only problem with JQuery is it's hard to maintain when the code or logic becomes bigger and more complex.
But, with ReactJS we could easily store and update the state variables however we want to. It's fast, easy to read, and most importantly beginner friendly.
Talk is cheap, show me the code. - Linus Torvalds
If you like to learn more, buy the best book for learning
ReactJS: https://amzn.to/33Z79Yl
Loving the article? Then please follow:
π Youtube
π Twitter
π Instagram
to keep you up to date with my new tutorials!!! πππ
Comments
Post a Comment