Blog>
Snippets

Rendering Children Nodes with Slots API

Provide an example of how to access and render children nodes passed to a component using the Slots API inside a render function.
class MyComponent extends React.Component {
  render() {
    // This uses the Slots API to render children passed to the component.
    // 'slots' prop contains named slots or a default slot.
    const { slots } = this.props;

    return (
      <div>
        {slots.default && slots.default.map(child => child)}
        {slots.header && <header>{slots.header.map(child => child)}</header>}
        {slots.footer && <footer>{slots.footer.map(child => child)}</footer>}
      </div>
    );
  }
}
In this code, a React component class named 'MyComponent' is defined. Inside the render function, it destructures a 'slots' prop which is expected to contain children nodes organized by names ('default', 'header', and 'footer'). It uses the && operator to check if any children exist for a specific slot and uses the map function to render each child node inside the appropriate wrapper element.