How to create Custom Toggle in React – Accordion

In here I am going to post, when a button click, a form will display as a toggle. so let’s start “How to create Custom Toggle in React” article. If you don’t have an idea about what I am saying, Please check the below image. You can understand what I said.

In here you can see a button called “Add new Supplier” (the blue color button). I am going to tell you, if you click that button, how can we see the below form will display?

you can see the suppler list section go down and the add new supplier form will display. That is how I going to code that. Let’s see!

Let’s start coding – How to create Custom Toggle in React – Accordion
import React from "react";


import {  Button } from 'react-bootstrap';

class supplier_Profile extends React.Component {

constructor(props) {
        super(props);
        this.state = {
            supplierState: false,
        }
}

 change_toggle = () => {
        if (this.state.supplierState) {
            this.setState({ supplierState: false })
        } else {
            this.setState({ supplierState: true })
        }
 }

render() {
        return (

{/* add new supplier button */}
<div className="row">
        <Button onClick={() => this.change_toggle()}>Add new Supplier</Button>
</div>

{/* Add new suppler form section */}
   <div className="row" style={{ display: this.state.supplierState == true ? 'block' : 'none'}}>

          <form>
          {/* you can customized your form. this is the form*/}
          </form>

   </div>

);
}
export default supplier_Profile;

First we have to design the layout. I mean the button, form and the list ( regarding to my design). After the that in the constructor we have to implement a state. I am going to to called it as “supplierState” and change it into “false”.

Then we have to implement a function to do that toggle thing. follow the below code to do that.

 change_toggle = () => {
        if (this.state.supplierState) {
            this.setState({ supplierState: false })
        } else {
            this.setState({ supplierState: true })
        }
  }

In here we get the state that we implement in the constructor and we check that to get the “true” value from it. when the value is true. the state will turn into true. So the next question is how can it be true??

Yeah, it is in the form section. refer the below code.

 <div className="row" style={{ display: this.state.supplierState == true ? 'block' : 'none'>

when we click the button, state will turn into true.

That’s it. short and sweet.

Thank you

if you want to check my other react tutorials, click here. you can refer so many react articles from the beginning. you can check my other articles, click here. If you have question contact me. stay with us.