简体   繁体   中英

How to use divs as radio button options in React.js

I'm trying to do two "radio-div" in React.js . A "radio-div" is a div that, if selected, changes its backgroung-color. Could anyone help me, please?

The final result must be like this

Thank you all

If a custom radio button is what you want, you can achieve that by hiding the radio button with display: none and target your div using css adjacent selector .

Check out this example I found online: https://codepen.io/AngelaVelasquez/pen/Eypnq

Look for input[type=radio]:checked ~ label

More Info: https://css-tricks.com/child-and-sibling-selectors/

Here's the stackblitz example. The idea is to add an active class on the selected radio div.

constructor() {
    this.state = {
        activeIndex: ''
    };

    this.radioButtons = [
        {
            text: 'India'
        },
        {
            text: 'England'
        }
    ]
}

updateRadioGroup(i) {
    this.setState({ activeIndex: i })
}

render() {
    let { activeIndex } = this.state;
    return (
        <React.Fragment>
            <h4> Who will win the match </h4>
            {
                this.radioButtons.map((element, i) => (
                    <div key={i} className={activeIndex === i ? 'radio_div active' : 'radio_div'} onClick={() => this.updateRadioGroup(i)}>
                        {element.text}
                    </div>
                ))
            }
        </React.Fragment>
    );
}

In my example i have added radio options meta in a state. Rendered the html with initial radio activeIndex ' ' empty (so that no radio is selected by default). Now whenever the user clicks on any of the div i update the activeIndex with the clicked radioDiv index and attach the active class on the respective radioDiv conditionally.

Thanks let me know if this is the case you wanted to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM