Created
July 28, 2018 17:52
-
-
Save dance2die/0a123f4e28b08cfc4f933e1f0880fcb6 to your computer and use it in GitHub Desktop.
"Applying a style on a clicked ReactJS component only not siblings" - Full source of App.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import { render } from "react-dom"; | |
import "./styles.css"; | |
const Child = ({ id, isClicked }) => ( | |
<div | |
className={isClicked ? `highlight` : ``} | |
>{`ID ${id} --- I am a child element`}</div> | |
); | |
class App extends Component { | |
state = { | |
// clicked: [] //works too | |
clicked: {} | |
}; | |
handleClick = i => { | |
this.setState(prevState => { | |
// const clicked = [...prevState.clicked]; // <- if clicked is declared as an array | |
const clicked = { ...prevState.clicked }; | |
console.log(`prevState.clicked, clicked`, prevState.clicked, clicked); | |
clicked[i] = !clicked[i]; | |
return { clicked }; | |
}); | |
}; | |
render() { | |
const items = [1, 2, 3, 4, 5].map((id, i) => { | |
return ( | |
<div key={id} onClick={() => this.handleClick(i)}> | |
<Child id={id} isClicked={this.state.clicked[i]} /> | |
</div> | |
); | |
}); | |
return ( | |
<div> | |
<div>{items}</div> | |
</div> | |
); | |
} | |
} | |
render(<App />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment