Get value of Children and props in React

Asked

Viewed 83 times

1

I need to get the children of a component and also its props. Someone knows how to do it?

Example:

<ElementPai value="text1" title="text2" colletion={valorArray}>
       <ElementFilho1/>
       <ElementFilho2/>
</ElementPai>

function ElementPai({children}){
       console.log(children);
       console.log(props); // <-- Não sei como acessar esta informação
}

1 answer

4


Em React, children is always a prop. Behold:

function App(props) {
  console.log(Object.keys(props)); // Veja que `children` é uma prop.

  return <div>{props.children}</div>;
}

ReactDOM.render(
  <App>
    <h1>Olá, mundo!</h1>
  </App>,
  document.querySelector('#app')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div>

Therefore, if you want to access the whole object prop, should stop using de-structuring:

function ElementPai(props){
  console.log(props.children);
  console.log(props); // <-- Agora você tem as _props_. Sempre teve, aliás. :)
}

You can still use unstructuring to access some props as you were doing with the prop children. Behold:

function ElementPai({ children, someOtherProp, andAnotherProp }){
  console.log(children);
  console.log(someOtherProp);
  console.log(andAnotherProp);
}

Just remember that children is a prop. :-)


Read this documentation to learn more about breakdown.

  • Hello there, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.