dimanche 24 janvier 2021

Can I decouple boolean state in React component

Like below simple react component code:

class Test extends React.Component {
    constructor(props){
        super(props)
        this.c1 = this.c1.bind(this);
        this.c2 = this.c2.bind(this);
        this.state = {
            a:false,
            b:false
        }
    }

    c1(e) {
        this.setState({a:true, b:false})
    }

    c2(e) {
        this.setState({a:false, b:true})
    }


    render() {
        return (
            <div>
                <div>
                    <input name="n" type="radio"  onChange={this.c1} />
                    <input name="n" type="radio"  onChange={this.c2} />
                </div>
                <div>
                    {
                        this.state.a && "aa"
                    }
                    {
                        this.state.b && "bb"
                    }
                </div>
            </div>
        )
    }
}

The code simply switch displaying 'aa' or 'bb' while click the radio button. But if I add a new radio button showing 'cc' to achieve the same function. I should:

  1. Add new state like 'c'
  2. Add new input HTML and implement its callback
  3. setState 'c' in this callback

All of those is ok, But I have to change the 'c1','c2' function that make my code coupling like:

class Test extends React.Component {
    constructor(props){
        super(props)
        this.c1 = this.c1.bind(this);
        this.c2 = this.c2.bind(this);
        this.c3 = this.c3.bind(this);
        this.state = {
            a:false,
            b:false,
            c:false,
        }
    }

    c1(e) {
        this.setState({a:true, b:false, c:false}) // add 'c:false' which coupled
    }

    c2(e) {
        this.setState({a:false, b:true, c:false}) // add 'c:false' which coupled
    }

    c3(e) {
        this.setState({a:false, b:false, c:true})
    }


    render() {
        return (
            <div>
                <div>
                    <input name="n" type="radio"  onChange={this.c1} />
                    <input name="n" type="radio"  onChange={this.c2} />
                    <input name="n" type="radio"  onChange={this.c3} />
                </div>
                <div>
                    {
                        this.state.a && "aa"
                    }
                    {
                        this.state.b && "bb"
                    }
                    {
                        this.state.c && "cc"
                    }
                </div>
            </div>
        )
    }
}

I think this situation is very common in React. So I want decoupling my code no matter how many radio buttons I add. I do not need to change the code just add code to satisfy the 'Open Closed Principle'.

Do you have any recommendation? Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire