guillaumek guillaumek - 1 month ago 11
React JSX Question

React: Give back the child new inserted element to parent for update the state

I have a parent component in React who display a list of items, also a state of (selectedList) who give an active class to this list item + display others components depending of the active class. This is the parent component.

In a child, I display the form where I can set a new list and an event onSubmit where I insert it in a Collection (meteor+mongo)

The problem is I can't make a relation between the new item (id) and the parent component cause I would like to select the list newly created (so give active class and display other components). Then I think I should update the state.selectedListId but I don't know how in a child, I can send it to the parent component ?

Here is few lines of codes:

PARENT ELEMENT (PAGE)

class TodosPage extends Component {

constructor(props) {
super(props);
this.state = {
listSelected: "",
};
}

selectList(listId) {
this.setState({ listSelected: listId });
}

renderLists() {
return this.props.lists.map((list) => (
<List
selectedItemId={this.state.listSelected}
selectList={() => this.selectList(list._id)}
key={list._id}
list={list}
countPendingTasks={this.countPendingTasks(list._id)}
/>
));
}

render() {
return (
<div className="container">
<ListForm />
<ListGroup>
{this.renderLists()}
</ListGroup>


CHILD ELEM (ListForm)

handleSubmit(event) {
event.preventDefault();

const name = ReactDOM.findDOMNode(this.refs.nameInput).value.trim();
Meteor.call('lists.insert', name, (err, listId) => {
console.log("in method insert = " + listId);
// HERE I CAN HAVE THE GOOD ID
});
ReactDOM.findDOMNode(this.refs.nameInput).value = '';
}

render() {
return (
<Form bsClass="col-xs-12" onSubmit={this.handleSubmit.bind(this)} >
<FormGroup bsClass="form-group">
<FormControl type="text" ref="nameInput" placeholder="Add New List" />
</FormGroup>
</Form>
);
}


Then, I can have the good ID in HandleSubmit but I don't know how to give it back to the parent component ..

Thanks for help

Answer

Have the parent (TodosPage) pass a function as a prop to its child (ListForm). Then onSubmit, have ListForm call the function.

class TodosPage extends React.Component {
  handleListFormSubmit = (goodId) => {
    // do something with goodId
  }
  render() {
    return <ListForm onSubmit={this.handleListFormSubmit} />;
  }
}

class ListForm extends React.Component {
  handleSubmit = (event) => {
    // get GOOD ID from the form, then call the parent function
    // [...]
    this.props.onSubmit(goodId);
  }
  render() {
    <Form onSubmit={this.handleSubmit}>
      {/* form stuff here */}
    </Form>
  }
}
Comments