John
John

Reputation: 1797

How to toggle a class on the body with React onClick

I have a button that opens a div that looks like a modal.

On click of this button, I want to add a class on to the body, then on click of a close button, I want to remove this class.

How would you do this in React functional component with useEffect / useState?

Upvotes: 1

Views: 962

Answers (1)

Antoni
Antoni

Reputation: 1433

You could use this.setState like this in Components

....
handleClick = () => {
  this.setState((state) => { 
    addClass: !state.addClass
  })
}

render () {
  const { addClass } = this.state

  return (
    <>
      <button onClick={this.handleClick}>Button</button>
      <div className={!!addClass && 'yourClassName'}>hello</div>
    <>
  )
}

And in function like this

function Example() {
  const [addClassValue, addClass] = useState(0);

  return (
    <div>
      <button onClick={() => addClass(!addClassValue)}>
        Click me
      </button>
      <div className={addClass ? 'yourClassName'}>hello</div>
    </div>
  )
}

But you do not need classes because React works with components and you can show your modal like

function Example() {
  const [addClassValue, addClass] = useState(false);

  return (
    <div>
      <button onClick={() => addClass(!addClassValue)}>
        Click me
      </button>
      // this Component will be only rendered if addClassValue is true
      {addClassValue && <ModalComponent />}
    </div>
  )
}

Upvotes: 1

Related Questions