admin管理员组

文章数量:1208153

Note: I don't really have an example code to present since I do not have any code related component injection (aside from these functional components that I have which are very self explanatory). I'll keep it short to save you time.

Let's say I have a <Toast /> component. I want to be able to "inject" that component to any page components. This will save me many lines of codes because I do not have to write conditions on every page component.

Note: I don't really have an example code to present since I do not have any code related component injection (aside from these functional components that I have which are very self explanatory). I'll keep it short to save you time.

Let's say I have a <Toast /> component. I want to be able to "inject" that component to any page components. This will save me many lines of codes because I do not have to write conditions on every page component.

Share Improve this question edited Jan 20 at 10:03 DarkBee 15.7k8 gold badges70 silver badges114 bronze badges asked Jan 20 at 9:44 sanaaasanaaa 376 bronze badges 1
  • 2 Import the component and return it in your render function? Please show an example. – 0stone0 Commented Jan 20 at 9:48
Add a comment  | 

1 Answer 1

Reset to default -1

There are two ways of doing so. Depends what you need.

  1. Composition with children (docs)

Toast component receives the page content as children and renders it alongside the toast message based on the showToast prop. Simple and easy to understand. Good for cases where toast logic is directly tied to the parent. But it's less flexible if you need more complex toast management like multiple toasts, queued toasts, or toasts triggered from deep within the child component's logic.

Example:

import React, { useState } from 'react';

const Toast = ({ children, showToast, toastMessage }) => {
  return (
    <div>
      {showToast && <div>{toastMessage}</div>}
      {children}
    </div>
  );
};

const PageComponent = () => {
  const [showToast, setShowToast] = useState(true);
  const [toastMessage, setToastMessage] = useState("Example toast");

  return (
    <Toast showToast={showToast} toastMessage={toastMessage}>
      <div>
        <h1>My Page</h1>
        <p>Some content here...</p>
        <button onClick={() => setShowToast(false)}>Hide Toast</button>
      </div>
    </Toast>
  );
};

export default PageComponent;
  1. Context API (docs)

ToastProvider component holds the state and logic for all toasts, effectively making toast management global. Any component can use the useToast hook to interact with the toast system, adding or removing toast messages. This is straightforward for simple use cases. Good for when you want to trigger toasts from anywhere in your application. But it becomes more complex if you need finer-grained control over individual toasts, such as styling or positioning specific toasts based on where they originate.

Example:

import React, { createContext, useContext, useState } from 'react';

const ToastContext = createContext();

const ToastProvider = ({ children }) => {
  const [toasts, setToasts] = useState([]);

  const addToast = (message) => {
    setToasts([...toasts, { id: Date.now(), message }]);
  };

  const removeToast = (id) => {
    setToasts(toasts.filter((toast) => toast.id !== id));
  };

  return (
    <ToastContext.Provider value={{ toasts, addToast, removeToast }}>
      {children}
      {toasts.map((toast) => (
        <div key={toast.id}>
          {toast.message}
          <button onClick={() => removeToast(toast.id)}>Close</button>
        </div>
      ))}
    </ToastContext.Provider>
  );
};

const useToast = () => {
  return useContext(ToastContext);
};

const PageComponent = () => {
  const { addToast } = useToast();

  return (
    <div>
      <h1>My Page</h1>
      <button onClick={() => addToast("Toast message from PageComponent")}>Show Toast</button>
    </div>
  );
};


const App = () => {
  return (
    <ToastProvider>
      <PageComponent />
    </ToastProvider>
  );
};


export default App;

本文标签: reactjsHow to inject a component to another componentStack Overflow