Madeline Ries
Madeline Ries

Reputation: 629

passing props to children missing props

How to pass props down to children?

const Tabs = ({ children, props }) => {
  console.log(props) //where is activeTab??
  return React.Children.map(children, child =>
    React.cloneElement(child, { ...props })
  )
}

const App = () => {
  return (
    <Tabs activeTab={1}>
      <div>tabs children</div>
    </Tabs>
  );
};

expecting props is an object where is has activeTab equal to 1 but above code gave me undefined?

https://codesandbox.io/s/vnz4z84vq7

Upvotes: 1

Views: 236

Answers (2)

Dario
Dario

Reputation: 6280

Both activeTab and children will be passed to your component as properties of props parameter, so to access them just change your component to:

const Tabs = (props) => {
  console.log(props.activeTab);
  console.log(props.children);
  return React.Children.map(children, child =>
    React.cloneElement(child, { ...props })
  )
}

or if you want to destructure you can write

const Tabs = ({ children, activeTab, ...props }) => { 
   console.log(activeTab);
   console.log(children);
   return React.Children.map(children, child =>
     React.cloneElement(child, { ...props })
   )
}

Upvotes: 1

Moti Korets
Moti Korets

Reputation: 3748

You dont need destructuring here. Just accept props as argument like this

const Tabs = ( props ) => {
// ... props.children - is your children object
}

If you want to use destructuring it would be like this

const Tabs = ( {children, activeTab } ) => {
// now children and activeTab is passed props
}

Upvotes: 1

Related Questions