JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Passing components as props in React

Author:JIYIK Last Updated:2025/03/16 Views:

We can pass components as props in React using the built-in children property. All the elements we pass between the component’s opening and closing tags will be assigned to the children property.

function Center({children}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {children}
    </div>
  );
}
export default function App() {
  const CustomHeading = () => {
    return <h2>Hello world</h2>;
  };
  // 👇️ pass children to the Center component
  return (
    <div>
      <Center>
        <CustomHeading />
      </Center>
    </div>
  );
}

This example shows how everything we pass between the component's opening and closing tags is assigned to the children property in React.

The component can deconstruct the children property from its props object and render it like we did in the Center component. Alternatively, we can pass the component directly as a prop to the child component.

// 👇️ 将按钮属性重命名为 Button(大写首字母)
function Wrapper({button: Button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Button />
    </div>
  );
}
export default function App() {
  const Button = () => {
    return <button onClick={() => console.log('button clicked')}>Click</button>;
  };
  // 👇️ 将button作为属性传递给 Wrapper 组件
  return (
    <div>
      <Wrapper button={Button} />
    </div>
  );
}

We pass the Button component as props to the Wrapper component.

WrapperThe component must rename the prop from button to Button (with a capital letter), because all component names must start with a capital letter.

If the Button component accepted props, we could pass them down when using it in the Wrapper component. Alternatively, we could pass the component as a prop to the child component and set its properties directly.

function Wrapper({button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {button}
    </div>
  );
}
export default function App() {
  const Button = ({text}) => {
    return (
      <button onClick={() => console.log('button clicked')}>{text}</button>
    );
  };
  return (
    <div>
      <Wrapper button={<Button text="Some button text" />} />
    </div>
  );
}

In this example, we Wrapperset the props of the Button component directly when passing it to the component.

注意, instead of passing the actual component function, we pass the return value of the Button component.

This means we have to use the prop as {button}, rather than Wrapperin the component <Button/>.

We can mix and match as well. Here's an Buttonexample of passing a component that takes a children prop and renders its children.

function Wrapper({button: Button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Button>
        <h2>一些按钮文本</h2>
      </Button>
    </div>
  );
}
export default function App() {
  const Button = ({children}) => {
    return (
      <button onClick={() => console.log('button clicked')}>{children}</button>
    );
  };
  return (
    <div>
      <Wrapper button={Button} />
    </div>
  );
}

Whatever we pass between the opening and closing tags of the Button component will be rendered.

When passing components as props, be careful about when you're passing an actual function component, e.g. button={Button}compared to when you're passing something that a function component returns, button={<Button text="一些按钮文本" />}e.g.

This is important because when we pass the actual function component, it can be used as <Button />. On the other hand, if you pass the return value of the function, it must be used as {button}.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:85 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial