Home > Back-end >  How to send info from a reusable input to the other components in React
How to send info from a reusable input to the other components in React

Time:12-09

I have different forms in different components. And one input, which I reuse in these components. If the user write smth in one component, another components should show this text too. And I don't know how to send this info to other components.

const InputComponent = () => {
  const [isInput, setisInput] = useState("");
  const changeInput = (event: ChangeEvent<HTMLInputElement>) => {
    setIsInput(event.target.value);
  };
  return <input type="text" value="isInput" onChange={changeInput} />;
};

And after it I need to reflect the inputed text in the other components.

const AnotherComponent = () => {
  return (
    <>
      <InputComponent />
      <button>send</button>
    </>
  );
};

CodePudding user response:

You have 2 main options:

  1. Define useState in AnotherComponent and send a setisInput as a parameter to InputComponent
  2. Use global store e.g. useContext or useSelector (if you are using redux). Then you can access this data everywhere in your application.

CodePudding user response:

I think a great way is to pass a callback handler as a property.

class AnotherComponent extends Component {
    constructor(props){
        super(props);
        this.updateView = this.updateView.bind(this);
    }
    
    updateView(someValue){
         // Do something with someValue
    }
    
    render(){
         return(
             <>
                 <InputComponent updateView={this.updateView} />
                 <button>send</button>
             </>
        );
    }
}

const InputComponent = (props) => {
   const [isInput, setisInput] = useState("");
   const changeInput = (event: ChangeEvent<HTMLInputElement>) => {
       setIsInput(event.target.value);
       
       // This line here
       this.props.updateView(event.target.value);
   };
   return <input type="text" value="isInput" onChange={changeInput} />;
};

That should work. I didn't change your setIsInput() but I do not think you need that.

You can look at the documentation here and also this might help.

  • Related