1

Can I pass the setPlaying as props? Or I have to do something like this example code?

Components Two and Three can be in their own file.

export const myComponent = () => {
  const [playing, setPlaying] = useState(false);

  const handleChange = (show) => {
    setPlaying(show);
  };

  return (
    <>
      <One />
      {!playing ? (
        <Two handleChange={handleChange} />
      ) : (
        <Three handleChange={handleChange} />
      )}
    </>
  ) 
};

const Two = ({ handleChange }) => {
  return (
    <Container>
      <Button onClick={{(e) => handleChange(true)}}>Click to Show Component Three</Button>
    </Container>
  );
};

const Three = ({ handleChange }) => {
  return (
    <Container>
      <Button onClick={{(e) => handleChange(false)}}>Click to Show Component Two</Button>
    </Container>
  );
};

sara lance
  • 493
  • 4
  • 16

2 Answers2

1

Of course. Wrapping setPlaying with handleChange is advantageous if you wish to do any further processing in myComponent. And the conditional rendering will prevent needless re-renders.

Charles Goodwin
  • 584
  • 5
  • 8
0

Yes, you can do that. Also, it is a good practice that you did with the handler.

ref: Passing setState to child component using React hooks

Bartek Smagacz
  • 140
  • 1
  • 5