Satish Awal Satish Awal - 7 months ago 73
React JSX Question

How to get data from Form from child component and pass it back to Parent Componet?

I want to add items to the lists.Items come from Child Component's form .

class App extends Component {
constructor(props) {
super(props);
this.state = {
lists: [], // this holds the name of each list
};
}

handleAddList(s) {
this.setState({lists:s});
};

render() {
return (
<div className="App">
<AddList addList={this.handleAddList.bind(this)} />
</div>
);
}
}


What should I write in handleSubmit function such that it return list to parent component?How to access input's value from form element?

class AddList extends Component {

handleSubmit(e) {
e.preventDefault();
this.props.addList(e.target.value); //Isn't this the way to get input from Form ...//
}

render() {
return (
<div id="addListDiv">
<form onSubmit={this.handleSubmit.bind(this)}>
<div id='addList'>
<label>What will be on your next list?&nbsp;
<input type='text' ref='id' id='newID'></input> //How ref is used?????
</label>
</div><br />
<input type='submit' value='Create List' />
</form>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root'));

Answer Source

To access your input value by ref you can use this.refs.id.value and to pass value from child to parent component you can use props.

let {Component} = React;

class App extends Component {   
  constructor(props) {
    super(props);
    this.state = {
        lists: [],  // this holds the name of each list
      };
    }

    handleAddList(s) {
      this.setState(prevState => {
      	return {lists: [s, ...prevState.lists]}
      });
    };

    render() {
      return (
        <div className="App">
          <AddList addList={this.handleAddList.bind(this)} />
          {this.state.lists.map((name, i) => <div key={i}>{name}</div>)}
        </div>
      );
    }
  }

class AddList extends Component {   
    handleSubmit(e) {
      e.preventDefault(); 
      let name = this.refs.id.value;
      if(name) {
      	this.refs.id.value = '';
        this.props.addList(name); 
      }
    }

    render() {
      return (
        <div id="addListDiv">
        <form onSubmit={this.handleSubmit.bind(this)}>
        <div id='addList'>
        <label>What will be on your next list?&nbsp;
        <input type='text' ref='id' id='newID'></input>   
        </label>
        </div><br />
        <input type='submit' value='Create List' />
        </form>
        </div>
      );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download