Skip to content

Instantly share code, notes, and snippets.

@dance2die
Created July 28, 2018 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dance2die/0a123f4e28b08cfc4f933e1f0880fcb6 to your computer and use it in GitHub Desktop.
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
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