reactjsreact-hooksreact-componentreact-context

How can I read a variable from another component in React?


I receive these two values from two options elements in a component using React. Question: How can I read these two variables from another component?

const handleInputChange = (e) => {   
    const valueFilterActive = document.getElementById("activeFilter").value;
    const valueFilterName = document.getElementById("bussFilter").value;
    alert(valueFilterName+valueFilterActive);   
 };

The second component code line:

 return (
    <> 
      <div className="col-md-4 p-2">
        <FirstComponent/>
  
      </div>
      <div className="col-md-8 p-1 ">
          <div className={ valueFilterActive  === 'Activado' ? "text-success" : "text-primary card mb-1"} key={link.id}>

Thanks a lot !!!


Solution

  • If you want read variables from another component you can use many ways. It depends how you chain those components.

    If the base value is in parent and you want to pass it to child use props https://reactjs.org/docs/components-and-props.html

    const element = <Welcome data1 ={valueFilterActive} data2 ={valueFilterName} />;
    
    function Welcome(props) {  
    return <h1>Hello, {props.valueFilterName} {props.valueFilterActive}</h1>;
    }
    

    If the base value is in child and you want to pass it to parent use callback function https://reactjs.org/docs/faq-functions.html

    But if its more complicated way i recommend using Context Hook https://reactjs.org/docs/hooks-reference.html#usecontext

    (PS: Also in react you don`t use getElementById but another hook called useRef https://reactjs.org/docs/hooks-reference.html#useref)