Reputation: 308
I want to be able to change the colour of some elements on my webpage to make it more accessible.
class App extends Component {
render() {
return (
<React.Fragment>
<div>This is a button</div>
<button>Click me!</button>
</React.Fragment>
);
}
}
If I had something like this in React, for example, how would I change the background colour of the div to red and the background of the button to blue when clicking the button? I have tried to use ref but I'm not too confident so any help would be appreciated, thank you.
Upvotes: 0
Views: 701
Reputation: 865
You can conditionally add/remove classes based on a state value.
function App() {
const [theme, setTheme] = useState('default');
handleClick = () => {
setTheme('red');
}
return (
<React.Fragment>
<div className={theme === 'red' ? 'red-background': 'default-background'}>This is a button</div>
<button onClick={handleClick}>Click me!</button>
</React.Fragment>
);
}
And then in your CSS you would have the classes defined
.red-background {
background: red;
}
.default-background {
background: white;
}
If you have lots of classes on your component, this is a useful package for conditionally joining class names together. https://github.com/JedWatson/classnames
Upvotes: 1
Reputation: 95
Simple explanation:
handleChangeBackground() {
this.setState({ bgColor: '#000' });
}
<div style={{ backgroundColor: this.state.bgColor }} className="articleParent">
<div>Article Content Section</div>
<colorButton handleBackground={this.handleChangeBackground} />
</div>
Inside of colorButton component:
render() {
return <Button onClick={this.props.handleBackground}>Change Color</Button>
}
The child is changing the background based on purely on props firing the function.
This might be wrong, I'm between conferences XD If not the case, I hope it helps!
Upvotes: 1
Reputation: 69
class App extends Component {
constructor(props) {
super(props);
this.state = {
divColor: "white",
buttonColor: "white"
};
}
handleButtonClick = () => {
this.setState({
divColor: "red",
buttonColor: "blue"
})
}
render() {
return (
<React.Fragment>
<div style={{background: this.state.divColor}}>This is a button</div>
<button
style={{background: this.state.buttonColor}}
onClick={this.handleButtonClick}
>
Click me!
</button>
</React.Fragment>
);
}
}
The new code:
Upvotes: 2