Skip to content

Instantly share code, notes, and snippets.

@dance2die dance2die/App.js
Created Jul 28, 2018

Embed
What would you like to do?
"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
You can’t perform that action at this time.