One of the things that state in react makes possible is the ability to trigger switches in display of a site, below I will show how to make a element toggle between hidden and visible. This can be used in many front end cases, for example you could use this to show a menu, change something like font style, etc.
Inside of the react app, I begin by making a class component with two pieces of state. The first piece of state labeled show is to determine whether or not our modal will be displayed or not.
Additionally, there is a second piece of state called 'buttonState', this piece of state will determine what the toggle button that we will click will display. We want the button to display 'open' when the display is closed and 'close' when the display is open.
Next within our render function, go ahead and create a button element with an event listener set to onClick={this.show} . We will create the show function below. Within the button element, we'll go ahead and check our buttonState and set the open/close text according to whether the buttonState returns true or false.
Within the main div element set className to change based upon the state of the 'show' state. In this example it alternates between classNames show and an empty string.
To finish up this particular file, we create our show function that swaps our state from false to true.
Finally we add the CSS class to trigger the desired change when the modal button is clicked.






Comments
Post a Comment