Home > Blockchain >  If I wrap a react components in one big react component will they share props
If I wrap a react components in one big react component will they share props

Time:09-27

I want to share props between all components but with a wrapper component For example:

const name = "Test"
return (
    <Wrapper myprops={name}>
      <Image/>
      <House/>
    </Wrapper>
)

So can I get the myprops from Image and House?

CodePudding user response:

Context API is used to share data between components in different nesting levels, you can read this from React doc:

Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.

For your case, your components Image and House are at the same level. Instead, you can use the composition and pass the props to your inner children like this:

import React, { cloneElement } from 'react';
import './style.css';

export default function App() {
  const name = 'Test';

  return (
    <Parent>
      <Wrapper myprops={name}>
        <Image />
        <House />
      </Wrapper>
    </Parent>
  );
}

function Parent({ children }) {
  return children;
}

function Wrapper({ children, ...props }) {
  return <>{children.map((child) => cloneElement(child, { ...props }))}</>;
}

function Image(props) {
  console.log(props);
  return <div>Image</div>;
}

function House(props) {
  console.log(props);
  return <div>House</div>;
}

This is a simple demo: https://stackblitz.com/edit/react-szxqwg

  • Related