0

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.

Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60
  • I advice you to start with something really simple like just get a click to log some information when pressing a div. Then go on to get the div to change color when clicking the div. Then create a component from that code that will expose the onClick event and that it takes a color as a prop. Then combine that in a new component that has a state that holds the current "selected" div. It is important when you are new to this to try it out yourself, that is the only way to really learn. If it is hard, make it easier by dividing it up in smaller parts. GLHF. – Gennon Jul 14 '16 at 05:44

2 Answers2

4

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>
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
0

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.

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

Lovepreet
  • 1
  • 1