DEV Community

Discussion on: Two way data binding in vue,react and vanilla js

Collapse
 
indoor_keith profile image
Keith Charles

I'm kind of confused why all three examples are all written very differently. React is changing an entire object when you type in a text field, while the vue and vanillaJS examples are only changing a single text value.

In any case, it might be worth mentioning, React doesn't actually have a two-way binding functionality. React follows a unitary data flow model, that is, data only flows down from parent to child, not vice versa. One way we get around this is by passing a callback to the child and letting that child run the callback with whatever value from the child we wish to provide.

Your React example sort of showcased this, but rather than change the value of the parent state from the child, you just change the value of the parent state using data from the parent state. Below would be an example of how we can imitate two-way binding in React:

const ChildComponent = (props) => {
  return (
    <input type="text" onChange={props.onChange} />
  );
};

const ParentComponent = () => {
  const [myMsg, setMyMsg] = useState('World');

  const handleChange = (event) => {
    const newMessage = event.target.value;
    setMyMsg(newMessage);
  }

  return (
    Hello, {myMsg}!
    <ChildComponent onChange={handleChange} />
  );
};
Enter fullscreen mode Exit fullscreen mode