简体   繁体   中英

How to create toggle class event in reactjs without jquery?

In jQuery, we can easily set toggle event like,

$('div').click(function(){
   $('div').toggleClass('active');
});

But how to implement this kind of thing in reactjs with jQuery.

To get toogling you to have to controll your state.

In this case i toggling the style attribute and you also can do it with your className attribute:

var Hello = React.createClass({
    getInitialState: function(){
        return {
          isVisible: true
        }
    },
    handleClick: function(){
        var notVisible = !this.state.isVisible;
        this.setState({
          isVisible: notVisible
        })
    },
    render: function() {
        var styleClass = this.state.isVisible? 'hidden':'visible';
        console.log(styleClass);
        return <div>
            <span style={{visibility: styleClass}}> Hello World</span>
            <button onClick={this.handleClick}>Click me</button>
        </div>;
    }
});

ReactDOM.render(
    <Hello />,
    document.getElementById('container')
);

Link to fiddle

I hope i will help you.

Thanks

Inside your react component class you could have the toggle flag as part of state data this.state.toggle . render method will see use this data to add class or not. We can bind a click listener to the button to to flip the flag in state.

getInitialState: function () {
    return {
        toggle: false
    };
},

clickHandler: function () {
    this.setState({ toggle: !this.state.toggle })
},

render: function () {
    var clsName = this.state.toggle ? 'active' : '';
    return <button className={ clsName } onClick={ this.clickHandler }>{ this.props.label }</button>;
}

Hope this helps. Good luck, have fun!

You can use the state for doing something like this in several ways:

first of all you need to declare the state variable in your componenet:

getInitialState: function () {
        return {
            isActive: false
        };
}

then you will need an onClick function

handleClick: function(){
   this.setState({isActive: !this.state.isActive});
}

Now you need to use this property in you render method

Option 1: concatenating class using a "short if" form

<div
   className={this.state.isActive? "active" : ""}
   onClick={this.handleClick}
>
    Some content...
</div>

Option 2: by using the React classet addons that you can find at https://github.com/petehunt/react-classset

<div
   className={
        React.addons.classSet({
            active: this.state.isActive
        })
   }
   onClick={this.handleClick}
>
    Some content...
</div>

Edit: I have just found out that the option2 si deprecated and they suggest instead to use this utility:

https://github.com/JedWatson/classnames

https://github.com/JedWatson/classnames

render () {
    var btnClass = classNames({
       'btn-pressed': this.state.isPressed,
    });
    return <button className={btnClass}>{this.props.label}</button>;
}

This code toggle btn-pressed class according buttons pressed state.

In functional component, we can use state & setState of useState hooks. The active className rendering depends on active state. And the toggle can be done by negating the previous active state.

const CarBrand = ({ brand }) => {
    const [active, setActive] = useState(false);

    return (
        <div
            onClick={() => setActive(prevState => !prevState)}
            className={`car-brand ${active ? "active" : ""}`}
        >
            {brand}
        </div>
    )
}

Example:

 const { useState } = React; const carBrands = [ "Audi", "BMW", "Citroen", "Ford", "Honda", "Jaguar", "Land Rover", "Mercedes", "Mini", "Nissan", "Toyota", "Volvo", ]; const CarBrand = ({ brand }) => { const [active, setActive] = useState(false); return ( <div onClick={() => setActive(prevState => !prevState)} className={`car-brand ${active ? "active" : ""}`} > {brand} </div> ) } function App() { return ( <div> <h1>Car Brands</h1> <div className="car-brands"> {carBrands.map((brand, i) => { return <CarBrand key={i} brand={brand} />; })} </div> </div> ) } ReactDOM.render(<App />, document.querySelector('.react'));
 .car-brands { font-family: Arial; color: #ffffff; background-color: DodgerBlue; width: 200px; } .car-brand { color: #ffffff; padding: 8px 16px; border: 1px solid transparent; border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent; cursor: pointer; user-select: none; } .car-brand.active { background-color: rgba(0, 0, 0, 0.1); }
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div class='react'></div>

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