Ali Rasoulian
Ali Rasoulian

Reputation: 439

Best solution binding for ReactJs?

In Angular2+ has easy solution for binding issue, we ngModel for two-way binding on various input and custom controls but in my opinion, reactJs support one-way binding issue . please describe best practice for two-way binding in ReactJs.

Upvotes: 0

Views: 39

Answers (1)

Rohini
Rohini

Reputation: 254

By two-way data binding, you mean to achieve an effect where if data is changed in child component it needs to change in the parent and vice-versa.

To achieve this what you can do is in your parent component define a function changeText

class Parent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            inputText: ""
        }
    }

    changeText(newText) {
        this.setState({
            inputText: newText
        })
    }

    ....
}

Pass function changeText to your child component.

In your child component use changeText as follows

function ChildComponent(props) {
    const handleChange = e => props.changeText(e.target.value)

    return (
        <input onChange={handleChange}></input>
    )
}

With this, if inputText changes from parent component or child component, the change will be reflected in both.

I hope this helps.

Upvotes: 1

Related Questions