Sunday 28 March 2021

Part 11 : Toggle Button With State

In this article I will show you how html div content show/hide on click of button. Both can be achieved with class and functional based component. Source code available here.
Function based component: To implement show, hide functionality need to maintain state on toggle button. Once button click flag will set to true and content shown on browser window, again toggle button click flag set to false and content hide on browser window.
I’m also using ternary operator in this article, let’s understand first ternary operator. It is not new already supported in modern languages like JavaScript, c#, java, python,…etc. It is nothing but short or compact form of if else.
Syntax : (expression) ? true condition statement : false condition statement
I have created button at line number 21 and created Toggledata variable at line number 12 with useState and created function toggleData which is called by toggle button for maintaining show and hide functionality. Turnery expression created on line number 23, ToggleData hold either true or false and based on result div show or hide (null). Run application and check browser window.
Click on toggle button and Employee List of IT department gets disappear.

Class based component:


Source code available here.
Replace below screen code in App.js.
For Component, need to import Component class written in line number 1. Its package provided by react library. Here Class is used instead of function at line number 5. For updating state in class based component setState function is used at line number 16. Which automatically update ShowEmployees under state array. Run application and check browser window. Its working same as it worked for function based component. I already provided screen above for functional component.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home