简体   繁体   中英

How can I apply classNames in react to change the background color of one of the child div in React

I have 3 children divs wrapped in one parent div as shown :

在此处输入图片说明

On click of each child div , I want its background-color to be changed to red. but if there is already one div with background-color red and some other div is clicked then its background color should be changed to white. There will be only one div with background color red. I am newbie to react. I read about classNames and states in React but can't find out how can I do this.

jsfiddle

Thanks in Advance.

You can do what you want like so

 var Сards = React.createClass({ getInitialState: function () { return { cards: [ { name: 'сard 1', isActive: false }, { name: 'сard 2', isActive: false }, { name: 'сard 3', isActive: false } ] }; }, handleClick: function (index) { const cards = this.state.cards.map((card, i) => { card.isActive = i === index ? true : false; return card; }) this.setState({ cards }) }, render: function() { const cards = this.state.cards.map((card, index) => { return <div key={ index } className={ card.isActive ? 'cards__card cards__card_active' : 'cards__card' } onClick={ () => this.handleClick(index) } > { card.name } </div> }); return <div className="cards"> { cards } </div>; } }); ReactDOM.render( <Сards />, document.getElementById('container') ); 
 .cards { border: 1px solid #000; padding: 5px; } .cards__card { width: 100px; height: 100px; border: 1px solid #000; margin: 5px; cursor: pointer; display: inline-block; } .cards__card_active { background: red; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"></div> 

I suggest you to try jQueryToggle.

$(document).ready(function(){
        $("button").click(function(){
            $("p").toggleClass("main");
        });
    });
Toggle class "main" for p elements

    

This is a paragraph.

This is another paragraph.

Click the button more than once to see the toggle effect.

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