Home > OS >  Pass a variable from Layout to children in next js
Pass a variable from Layout to children in next js

Time:01-06

I have the following code `

import { useState, useEffect } from 'react'
import LayoutContent from './layout_content';
type Props = {
  children: JSX.Element | JSX.Element[]
}
const Layout = ({ children }: Props) => {
  const [selected, setSelected] = useState(countries[0]);
  const country= selected.id
  return (
    <>
      <Sidebar onClick={toggle} sidebar={open} />
     <LayoutContent sidebar={open} countriesWithsrc ={countriesWithsrc}  selected={selected} lected={setSelected} >
      {children}
     </LayoutContent>
    </>
  )
}
export default Layout;

` How do I pass the variable country from the Layout component to the children without state management ?.I.e I want to drill it.

CodePudding user response:

If you don't want any state management you can use React.Children. It provides utilities to work with the children prop. React.Children.map will run a method for every immediate child of the component. You can use cloneElement along with that to create a clone of your element by passing in extra properties. Infact you can even modify the children of an element you are cloning, but that is not the ask here.

Do note that context would be the better way to do it.


const Layout = ({ children }: Props) => {
....
....
const modifiedChildren = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { testProp : 'test' });
    }
    return child;
  });
....
....

return (
    <>
      <Sidebar onClick={toggle} sidebar={open} />
     <LayoutContent sidebar={open} countriesWithsrc ={countriesWithsrc}  selected={selected} lected={setSelected} >
      {modifiedChildren}
     </LayoutContent>
    </>
  )
}

  • Related