-1

In Reactjs if I have two child components of an App component, can I take input from one component and output it in the other child component?

class App extends Component{

    render(
       <Input/>  
       <Output/>  
    )

}

Input = () => { //input } 



Output = () => { //output }  
Alberto
  • 1,348
  • 2
  • 14
  • 28
thierved
  • 13
  • 5

3 Answers3

0

It's simple. Use the same state value for both components in the parent component:

class App extends Component{

    constructor(props){
        super(props);
        this.state = {
            value: ''
        }

        onValueChange = thisonValueChange.bind(this);
    }

    onValueChange(e) {
        e.preventDefault();
        setState({
            value: e.target.value
        });
    }

    render(){
        return(
            <Input value={this.state.value} onChange={this.onValueChange} />  
            <Output value={this.state.value}/>  
        );
    }

}

Input = (props) => { 
    <input value={props.value} onChange={props.onValueChange}>
} 


Output = (props) => <div>{props.value}</div>);
Ihor Lavs
  • 2,315
  • 2
  • 15
  • 26
0

You can handle the data in the App component via state by passing a handler down to the Input component and then pass the state value down to the Output component like

const Input = props => <input onChange={props.handleChange} />
const Output = props => <span>{props.data}</span>

class App extends Component {
  state = {data:""}
  handleChange = e => {
    this.setState({ data: e.target.value })
  }
  render() {
    return (
      <div>
        <Input handleChange={this.handleChange} />
        <Output data={this.state.data} />
      </div>
    )
  }
}
supra28
  • 1,646
  • 10
  • 17
0
`export class Parent extends React.Component{
     constructor(props){
         super(props);
         this.state={
             name:'',
             sendData:false
         }
     }

      render(){
          return (<div><input type="text" onChange={(event)=> 
              {this.setState({
                    name:event.target.value,

               })
           }) 
           />
            //sendData can be made true on a  button click
            {this.state.sendData ?(<div><Child name={this.state.name} 
                                   />
                                   </div>):null}
      </div>)}
 }`

Display the data of Parent in the child component.

   `export class Child extends React.Component{
     render(){
          return (<div>Name is :{this.props.name}</div>) 
      }
    }`
Erick
  • 1,098
  • 10
  • 21