SoFunction
Updated on 2025-04-14

Sample code to implement slot functionality of Vue in React

Core concept

In Vue, slots allow parent components to pass HTML structures to children, enabling more flexible component reuse. Named slots allow the parent component to pass multiple different HTML structures to the child component, while scoped slots allow the child component to pass data to the parent component so that the parent component can render different content based on this data.

In React, we don't have a direct concept of slots, but it can be done throughand functions as props to implement similar functions.

Implement named slots

In React, we can simulate named slots by passing different props. Each prop represents a slot, and its value can be a React element or function.

Sample code

// components/
import React from 'react';

function Layout({ header, content, footer }) {
  return (
    <div className="layout">
      <header className="layout-header">{header}</header>
      <main className="layout-content">{content}</main>
      <footer className="layout-footer">{footer}</footer>
    </div>
  );
}

export default Layout;
// 
import React from 'react';
import Layout from './components/Layout';

function App() {
  return (
    &lt;Layout
      header={&lt;h1&gt;Website title&lt;/h1&gt;}
      content={&lt;p&gt;This is the main content of the website。&lt;/p&gt;}
      footer={&lt;small&gt;all rights reserved © 2024&lt;/small&gt;}
    /&gt;
  );
}

export default App;

Code explanation

  • :
    • Define aLayoutComponent, it receives three props:headercontentandfooter
    • The values ​​of these props can be any React element, for example<h1><p><span>wait.
    • LayoutThe component renders these props into the corresponding HTML structure.
  • :
    • IntroducedLayoutComponents.
    • existAppIn the component, weLayoutThe component passes three props:
      • header:one<h1>element, as the title of the page.
      • content:one<p>Element, as the main content of the page.
      • footer:one<small>element, as the footer of the page.
    • In this way, we implement functions similar to Vue named slots.

Implement scope slots

In React, we can implement scoped slots by passing functions as props. The child component calls this function and passes the data to it as a parameter, and the parent component renders different content based on this data.

Sample code

// components/
import React from 'react';

function List({ items, renderItem }) {
  return (
    <ul>
      {((item, index) => (
        <li key={index}>{renderItem(item, index)}</li>
      ))}
    </ul>
  );
}

export default List;
// 
import React from 'react';
import List from './components/List';

function App() {
  const items = [
    { id: 1, name: 'apple', price: 5 },
    { id: 2, name: 'banana', price: 3 },
    { id: 3, name: 'orange', price: 4 },
  ];

  const renderItem = (item, index) =&gt; {
    return (
      &lt;div&gt;
        {index + 1}. {} - price: {}Yuan
        { &gt; 4 &amp;&amp; &lt;span style={{ color: 'red' }}&gt; (expensive)&lt;/span&gt;}
      &lt;/div&gt;
    );
  };

  return (
    &lt;div&gt;
      &lt;h1&gt;Product List&lt;/h1&gt;
      &lt;List items={items} renderItem={renderItem} /&gt;
    &lt;/div&gt;
  );
}

export default App;

Code explanation

  • :
    • Define aListComponent, which receives two props:itemsandrenderItem
    • itemsis an array containing data to be rendered.
    • renderItemis a function that renders each list item.
    • ListComponent traversalitemsarray and call each elementrenderItemfunction, passing elements and indexes as parameters to it.
    • renderItemThe return value of the function will be rendered to<li>in the element.
  • :
    • IntroducedListComponents.
    • Define aitemsArray, containing some product data.
    • Define arenderItemfunction, it receives aitemandindexAs an argument, and return a React element.
    • existrenderItemIn the function, weitemThe data renders different content, such as product name, price, and whether it is too high.
    • existAppIn the component, weListThe component is passeditemsArray andrenderItemfunction.
    • In this way, we implement functions similar to Vue scoped slots.

More complex examples

For a better understanding, let's look at a more complex example, which contains multiple named slots and scoped slots.

// components/
import React from 'react';

function Card({ header, content, actions, renderFooter }) {
  return (
    <div className="card">
      <div className="card-header">{header}</div>
      <div className="card-content">{content}</div>
      <div className="card-actions">{actions}</div>
      <div className="card-footer">{renderFooter && renderFooter()}</div>
    </div>
  );
}

export default Card;
// 
import React from 'react';
import Card from './components/Card';

function App() {
  const user = {
    name: 'Zhang San',
    age: 30,
    email: 'zhangsan@',
  };

  const renderFooter = () =&gt; {
    return (
      &lt;p&gt;
        User Information:{},{}age,Mail:{}
      &lt;/p&gt;
    );
  };

  return (
    &lt;Card
      header={&lt;h2&gt;User Information&lt;/h2&gt;}
      content={&lt;p&gt;This is the user's details。&lt;/p&gt;}
      actions={
        &lt;button onClick={() =&gt; alert('edit')}&gt;edit&lt;/button&gt;
      }
      renderFooter={renderFooter}
    /&gt;
  );
}

export default App;

Code explanation

  • :
    • Define aCardComponent, which receives four props:headercontentactionsandrenderFooter
    • headercontentandactionsare named slots, their values ​​can be any React element.
    • renderFooteris a function that renders the footer of a card, which is a scoped slot.
    • CardThe component renders these props into the corresponding HTML structure.
  • :
    • IntroducedCardComponents.
    • Define auserObject, containing some user information.
    • Define arenderFooterFunction, which returns a React element containing user information.
    • existAppIn the component, weCardThe component passes four props:
      • header:one<h2>element, as the title of the card.
      • content:one<p>Elements, as the main content of the card.
      • actions:one<button>Element, as the action button for the card.
      • renderFooter: A function that renders the footer of a card.
    • In this way, we implement the functions of multiple named slots and scoped slots.

Summarize

Through the above example, we can see that in React, we can passand functions as props to implement Vue-like named and scoped slots.

  • Named slots: Simulated by passing different props, each prop represents a slot, whose value can be a React element or function.
  • Scope slots: Simulate by passing functions as props, the child component calls this function and passes the data as parameters to it, and the parent component renders different content based on these data.

Although this approach is not as concise as Vue's slot syntax, it is flexible enough to meet the needs of most scenarios.

The above is the detailed content of the sample code for implementing Vue's slot function in React. For more information about React's slot function in implementing Vue, please pay attention to my other related articles!