I have two input boxes (one each) in two components. Whenever I change the value in any of the input boxes I need to change the value in another input box. Which means updated value need to pass between the parent to child and child to parent using props in React.
Asked
Active
Viewed 1.3k times
0
-
put some code to show us what have you done from now ;) – ekans Feb 13 '18 at 13:02
-
Possible Duplicate of [How to pass data from child component to its parent in ReactJS?](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs/38397755#38397755) – Shubham Khatri Feb 13 '18 at 16:59
1 Answers
1
If I understand your question right:
Update: to set the value in both inputs, you could do the following:
- pass a
setState
function from the parent component to both child components - inside of the each of the child components, use this passed function on the input field
onChange
handler - this function in turn will set the state in the parent component - pass the parent's state to both of the child components
- inside of the each of the child components, use the component prop with the parent's state to set the value of in the input fields
Here is a working demo with this workflow, or you can run the snippet below:
class App extends React.Component {
state = { inputValue: '' }
handleChange = e => {
this.setState({inputValue: e.target.value})
}
render(){
const {inputValue} = this.state;
return(
<div className='App'>
<FirstInput handleChange={this.handleChange} inputValue={inputValue}/>
<SecondInput handleChange={this.handleChange} inputValue={inputValue}/>
</div>
);
}
}
const FirstInput = ({handleChange, inputValue}) => <input placeholder='first input' onChange={handleChange} value={inputValue}/>;
const SecondInput = ({handleChange, inputValue}) => <input placeholder='second input' onChange={handleChange} value={inputValue}/>;
ReactDOM.render(<App />, document.getElementById('root'));
.App {
display: flex;
justify-content: space-around;
}
input {
padding: 0.5rem;
font-size: 1em;
flex-grow: 0.4;
}
<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>

Dan Kreiger
- 5,358
- 2
- 23
- 27
-
thanks for the answer but the input1 also need to change when we enter or delete a value in input2 as welll – saran Feb 13 '18 at 17:23
-
@saran I've updated my answer. Is this what you are looking for? You can also clear the input field `onFocus` if you want the input to clear when you select it - I wasn't sure if you wanted that though. – Dan Kreiger Feb 13 '18 at 18:50