Reputation: 305
I've 3 react components which are basically 3 divs. Now I select one component out of them by clicking.now I want to change the selected component's background color to black. If I select another component then previously selected component should back to normal. How can I do that?
Upvotes: 0
Views: 3045
Reputation: 385
import React, { Component } from 'react'
export default class YourClass extends Component {
constructor(props) {
super(props)
this.state = {
color: 'black'
}
this.changeColor = this.changeColor.bind(this)
this.changeColor2 = this.changeColor2.bind(this)
}
changeColor() {
this.setState({
color: 'red'
})
}
changeColor2() {
this.setState({
color: 'green'
})
}
render() {
return (
<div style={{ backgroundColor: this.state.color }}>
<button onClick={this.changeColor} />
<button onClick={this.changeColor2} />
</div>
)
}
}
This is a very rudimentary way to do it, by default the div is black, when you click the first button you can change it to red and the second button to green
You can use this simple logic for several things
Upvotes: 0
Reputation: 8683
Here's a simple solution:
.App {
display: flex;
}
.box {
width: 150px;
height: 150px;
margin: 20px;
padding: 20px;
}
import React from "react";
import "./styles.css";
export default function App() {
const [bg, changeBGColor] = React.useState(1);
return (
<div className="App">
<div
className="box"
onClick={() => changeBGColor(1)}
style={{
backgroundColor: bg === 1 ? "black" : "red"
}}
/>
<div
className="box"
onClick={() => changeBGColor(2)}
style={{
backgroundColor: bg === 2 ? "black" : "yellow"
}}
/>
<div
className="box"
onClick={() => changeBGColor(3)}
style={{
backgroundColor: bg === 3 ? "black" : "green"
}}
/>
</div>
);
}
Paste this in a Codesandbox to see the output.
Here, I'm giving using a React hook which takes in a unique id. If it's set, then that component will be black
.
So 1st div
is black
by default. If I click on 2nd div
, I change the value of bg
to 2
& in the style
property I check if 2
is selected then set black
color. Similarly, I do the same thing for 3rd div.
Upvotes: 2
Reputation: 1480
assuming those components have their own unique properties (or you should add them) you can add modify their className like className={this.state.selectedComponent==="uniqueID" ? "activeClassName" : ""} while having a state property (selectedComponent) which is set to that unique property upon onClick
Upvotes: 0