Reputation: 601
I have some radio buttons which I've styled to look like this:
As of now they look the same even when checked. I want to make it so that when you check one, instead of just being a ring, it's filled in with the same color like this:
How would I do this in React? I can add a background color to the element in the CSS but it won't be each element's own color (unless I create a separate class for each element but that seems very long considering I have a lot of these).
Here's the code:
import React from 'react';
import Options from './Options.jsx';
class Icing extends React.Component {
render() {
return (
<Options>
<input type="radio" className="circle" name="icing" defaultValue={1} id="white" style={{border: "10px solid #EFE5CE"}} />
<label class="radio" htmlFor="white"></label>
<input type="radio" className="circle" name="icing" defaultValue={2} id="pink" style={{border: "10px solid #EF959D"}} />
<label class="radio" htmlFor="pink"></label>
<input type="radio" className="circle" name="icing" defaultValue={3} id="red" style={{border: "10px solid #90DDD0"}} />
<label class="radio" htmlFor="red"></label>
</Options>
);
}
};
export default Icing;
Thanks!
EDIT
Alright so I added this:
constructor() {
super();
this.state = {checked: false};
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked
})
}
And this to the button as a test:
onChange={this.handleChange} checked={this.state.checked} style={{backgroundColor: this.state.checked ? 'red' : 'white'}}
And sure enough the background does change on click, but it doesn't go back to normal when I click another button. I have to click it again to make the color disappear.
Upvotes: 6
Views: 24261
Reputation: 2460
You can control CSS with javascript in React.
render() {
const styles = {
radioWhite: {
border: "10px solid #90DDD0",
},
radioPink: {
border: "10px solid #EF959D",
},
radioRed: {
border: "10px solid #90DDD0",
}
};
// pink on click
styles.radioPink['backgroundColor'] = '#EF959D';
return (
<Options>
<input type="radio" className="circle" name="icing" defaultValue={1} id="white" style={styles.radioWhite} />
<label class="radio" htmlFor="white"></label>
<input type="radio" className="circle" name="icing" defaultValue={2} id="pink" style={styles.radioPink} />
<label class="radio" htmlFor="pink"></label>
<input type="radio" className="circle" name="icing" defaultValue={3} id="red" style={styles.radioRed} />
<label class="radio" htmlFor="red"></label>
</Options>
);
}
I have more examples in my react-gallery project: https://github.com/bfwg/relay-gallery
Upvotes: 1
Reputation: 353
You can use onChange
input's attribute to handle a check. In the handle function, you can change component's state
. Use state to set style. For example:
style={{backgroundColor: this.state.isCheck ? 'red': 'white'}}
Upvotes: 1