Need help and example with understanding pass state o a child component as `props` :(

Tell us what’s happening:
Describe your issue in detail here.

Can someone show me an example of
"You pass state data to a child component as props . "

I want to understand what does this
" Note that if you make a component stateful, no other components are aware of its state . Its state is completely encapsulated, or local to that component, unless you pass state data to a child component as props . This notion of encapsulated state is very important because it allows you to write certain logic, then have that logic contained and isolated in one place in your code."

statement means
Thank you :slight_smile:

They are functions, the stuff inside the function stays inside the function. In React, the stuff you define in a component stays inside that component unless you explicitly pass it to something else (by calling another function).

Props is an object that is one of the arguments given to those functions.

This is at core, how the language works: you can’t access things inside a function from outside the function, unless you pass things out from it. React does some extra stuff in addition, but essentially it works the same.

Example (I’ve used function syntax but classes work essentially exactly the same way):

function Example () {
  const [name, setName] = React.useState("");

  return (
    <>
      <p>My name is {name || "unknown" }</p>
      <NameInput changeHandler={setName} value={name} />
    </>
  );
}

function NameInput (props) {
  return (
    <input type="text" value={props.value} onChange={props.changeHandler} />
  );
}

There is a function Example. There is a function NameInput. They both take an argument which you’d call props. The first one doesn’t use any props, so you can leave it off. The second on takes { value, changeHandler } where value is a string and changeHandler is a function.

1 Like