Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React equivalent to ng-model

Tags:

reactjs

New to React, I have a TextField that I want to "bind" a value to it, I want it to change the value if the user enters value into the TextField and update the TextField if the value change through some API call.

Is there a way to do it ?

like image 781
Pacman Avatar asked May 11 '17 23:05

Pacman


2 Answers

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.

like image 90
Aneesh Ashutosh Avatar answered Nov 02 '22 17:11

Aneesh Ashutosh


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>
    );
  }
}
like image 38
TheRealMrCrowley Avatar answered Nov 02 '22 17:11

TheRealMrCrowley