1

I am just getting started with React and not able to figure this out.

    <Select>
      <Search term={this.state.filename} />
    </Select>

Select component is for selecting a file, I want to set the initial value of input text inside the Search component to be the filename.

Here is the Search component

  <form onSubmit={this.handleSubmit}>
    <input
      type="search"
      value={this.props.term}
      onChange={this.handleChange}
    />
  </form>

Now, whenever user tries to change the value of input from the initial value set by the parent, I set the state of the child with the new input value but this triggers re-render of the child which resets the input value. What is the correct way around this?

What I am currently thinking is if I assign the value of input like this value={this.props.term} , then changing the state will trigger re-render of the child with the filename as the default value and user will be able to edit it.

nandwana92
  • 105
  • 2
  • 11

2 Answers2

1

Try have onChange on Search be delegated to a props so that your parent will be the one that sets the value when onChange is called on child.

onChange={this.props.onInputChange}
Warren Mira
  • 242
  • 1
  • 7
0

Here you are using value={this.props.term}, which makes the input a controlled component. The value here will always be same as this.props.term, which is the state from parent component. <Search term={this.state.filename} />

I guess what you really want to do here is change parent's state inside child component.

Then you should pass a function from parent component to child component. The function will change the state of parent component. You should define Something in parent component like these:

onChildInputChange(term) {
    this.setState({term: term })
}

Then pass it to child component through props

<Select>
   <Search term={this.state.filename} onChildInputChange={this.onChildInputChange} />
</Select>

so that in child component you can do this:

 <form onSubmit={this.handleSubmit}>
    <input
      type="search"
      value={this.props.term}
      onChange={()=>{this.props.onChildInputChange()}}
    />
  </form>
Youbent
  • 61
  • 1
  • 6