Nicc
Nicc

Reputation: 777

React how to pass a component with its props to another component

I need to pass a wrapper to the component Test. This wrapper could be anything and it needs to have its own props (function, bool, string, whatever).

function App() {
  return (
    <div className="App">
      <h1>Yo</h1>
      <Test Wrapper={<CustomWrapper text={"yes"} />} />
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

The component Test receives it as a prop and renders it including the children (here 'Nope')

function Test({ Wrapper }) {
  return (
    <div>
      <Wrapper>
        <div>Nope</div>
      </Wrapper>
    </div>
  );
}

What is the right pattern to do that?

Upvotes: 1

Views: 85

Answers (1)

keikai
keikai

Reputation: 15146

Pass the child as a prop would work

import React from "react";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Yo</h1>
      <Test Wrapper={CustomWrapper({ text: "yes" })} />
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const Test = ({ Wrapper }) => {
  return (
    <div>
      <Wrapper children={<div>Nope</div>} />
    </div>
  );
};

const CustomWrapper = props => ({ children }) => {
  return (
    <div>
      {children}
      {props.text}
    </div>
  );
};

enter image description here

Edit awesome-mccarthy-mpxji

Upvotes: 1

Related Questions