简体   繁体   中英

How do I toggle div class depending on which button has been clicked in React?

I'm creating a product page in my React (ES6) app to display different product features. There will be a button for each feature and a div for each feature displaying the information.

When a button is clicked it should toggle an active class to the relevant content div, however I'm fairly new to React so I'm unsure how this would be done with regards to toggling the class.

My code as it stands is as follows:

import React, { useContext } from "react";
import { Link } from "react-router-dom";
import '../App.scss';
import ProductData from "./data/ProductData";
import { ChoicesContext } from "../context/ChoicesProvider";

class Product extends React.Component {

  constructor(props) {
      super(props);
      this.toggleClass= this.toggleClass.bind(this);
      this.state = {
          active: false,
      };
  }
  toggleClass() {
      const currentState = this.state.active;
      this.setState({ active: !currentState });
  };

  static contextType = ChoicesContext;

  render() {
    const { choices } = this.context;
    const CurrentProduct = ProductData.filter(x => x.name === choices.productSelected);

    return (
      <>

        <div className="product wrapper d-md-flex">

          <main>

            <Link
              {/* Need this to toggle active class to <Overlay text={'Overlay 1'} /> */}
              className="btn-reverse overlay"
            >TOC</Link>

            <Link
              {/* Need this to toggle active class to <Overlay text={'Overlay 2'} /> */}
              className="btn-reverse overlay"
            >Puresure</Link>

            <Overlay text={'Overlay 1'} />
            <Overlay text={'Overlay 2'} />

          </main>
        </div>
      </>
    )
  }
}
export default Product;

class Overlay extends React.Component {
  render() {
    return (
      <div className="overlay">
        <h2>{this.props.text}</h2>
      </div>
    )
  }
}

i recommend you to use npm package classNames

import classNames from 'classnames';

...
const classes = classNames('btn-reverse', 'overlay', {
  'active': this.state.active
})

...
<div className={classes}> .... </div>

It works by the next scenario: if this.state.active === true, then classes will be 'btn-reverse overlay active' else 'btn-reverse overlay'

Also, I can recommend you don't filter your products in render, try to avoid it. Because no matter why your component will re-render, you always will be filter products

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM