Home > Back-end >  let variable null when passing from parent to child | React
let variable null when passing from parent to child | React

Time:10-08

I have a variable that I don't want to bind to state in React. So I declared it as let with initial value as null. Later with event I set its value in parent and then pass it to child. But in child its value is getting null. Not sure what mistake I am making. Below is the code.

function Parent() {

    const[showChild, setShowChild] = useState(false);
    let data = null;

    const setData = () => {
      data = 'Test';
      setShowChild(true);
      console.log('function called');
    };

    return (
      <>
        <button onClick={setData}>
          Click Me
        </button>
        {showChild && <Child data={data} />}
      </>
    );
}

function Child({data}) {
    console.log('data '    data);
    return (
      <>
        <h2>
          {data}
        </h2>
      </>
    );
}

ReactDOM.render(
  <Parent />, 
  document.getElementById('mountNode'),
);

CodePudding user response:

If you want to persist state you have to use useState as you did in the first line. so instead of manually let data ... and const setData you should have something like the following:

const [data, setData] = useState(null)

CodePudding user response:

You sould use useState, whenever the state changes in parent, child will be render again.

I changed your example a little bit to show you what happen exactly, child just shows the value that parent has sent.

const {useState} = React;

const Parent=()=> {
 const[showChild, setShowChild] = useState(false);
 const[data, setData] = useState(0);
    //let data = null;

    const handleClick = () => {
      setData((prev=>prev 1));
      setShowChild(true);
      console.log('function called');
    };
    return (
      <div>
          <button onClick={handleClick}>
          Click Me
        </button>
        {showChild && <Child data={data} />}
      </div>
    );
}
const Child=({data})=> {
    console.log('data '    data);
    return (
      <div>
        <h2>
          {data}
        </h2>
      </div>
    );
}


ReactDOM.render( <Parent/> ,
  document.getElementById("mountNode")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="mountNode"></div>

  • Related