React equivalent to ng-model

The way to do this in React is with state. Here's an example in JSX:

import React from 'react';

export default class MyForm extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      text: 'default',
      text2: 'default'
    }
  }

  onChange(e) {
    var obj[e.target.name] = e.target.value
    this.setState(obj);
  }

  render() {
    return (
      <div>
        <input type="text" name="text" value={this.state.text} onChange={this.onChange} />
        <input type="text" name="text2" value={this.state.text2} onChange={this.onChange} />
      </div>
    );
  }
}

You can do this using state and onChange. Simple example included below:

<TextField
  onChange={(name) => this.setState({name})}
  value={this.state.name}
/>

A guide for updating TextInput based on a variable is located in the docs.


The same thing with React hook

import React,{useState} from 'react';

export default MyForm = () => {
  const [text, setText] = useState('default')
  const [text2, setText2] = useState('default')

  return (
    <div>
      <input type="text" name="text" value={text} onChange={(e)=> setText(e.target.value)} />
      <input type="text" name="text2" value={text2} onChange={(e)=> setText2(e.target.value)} />
    </div>
  )
}

Tags:

Reactjs