Is passing data from child component to parent is valid?

Tell us what’s happening:

  1. Below code is showing webpage with static text from Text component and button from Button component
  2. My question is
    2.1 Is it valid to pass data from child component Button to parent component App ?
    2.2 button click event will generate random number which will be sent to App, which later sends to Text component to show new text
    2.3 Am I thinking correctly to implement solution here ?
    2.4 I’m using only functional components here

Your code so far

import React from 'react';
import Text from './components/Text';
import Button from './components/Button';

function App() {
  return (
    <div id="quote-box">
      <Text />
      <Button />
    </div>
  );

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36.

Challenge: Build a Random Quote Machine

Link to the challenge:

You can define a function inside App and pass it to Button as a prop and invoke it inside the event handler with the random number as argument. It is valid depending on the situation you are in.

1 Like

Generally, when you have couple components that depend on the same data (in your situation, you want to update Text when Button is clicked) what you want to do is manage this data in the closest parent component (in your case App).

It’s called lifting state up. Having this in mind you could do for example something like this:

function App() {
  const [value, setValue] = useState();

  const handleClick = () => setValue(Math.random());

  return (
    <div>
      <Text text={value} />
      <Button onClick={handleClick} />
    </div>
  )
}
1 Like