Search code examples
htmlcssreactjsclass-names

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 :

enter image description here

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.


Solution

  • 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>