Skip to content Skip to sidebar Skip to footer

React.js "global" Component That Can Be Created Multiple Times

I can't get my head wrapped around this. The problem: let's say there's an app and there can be some sort of notifications/dialogs/etc that i want to create from my code. I can hav

Solution 1:

You could use React Context for this.

You create a React context at a high level in your application and then associate a values to it. This should allow components to create / interact with notifications.

exportconstNotificationContext = React.createContext({
  notifications: [],
  createNotification: () => {}
});

classAppextendsComponent {
  constructor() {
    super();

    this.state = {
      notifications: []
    };

    this.createNotification = this.createNotification.bind(this);
  }

  createNotification(body) {
    this.setState(prevState => ({
      notifications: [body, ...prevState.notifications]
    }));
  }

  render() {
    const { notifications } = this.state;

    const contextValue = {
      notifications,
      createNotification: this.createNotification
    };
    return (
      <NotificationContext.Providervalue={contextValue}><NotificationButton />
        {notifications.map(notification => (
          <Notificationbody={notification} />
        ))}
      </NotificationContext.Provider>
    );
  }
}

The notifications are stored in an array to allow multiple at a time. Currently, this implementation will never delete them but this functionality can be added.

To create a notification, you will use the corresponding context consumer from within the App. I have added a simple implementation here for demonstration purposes.

import { NotificationContext } from"./App.jsx";

constNotificationButton = () => (
  <NotificationContext.Consumer>
    {({ notifications, createNotification }) => (
      <buttononClick={() => createNotification(notifications.length)}>
        Add Notification
      </button>
    )}
  </NotificationContext.Consumer>
);

You can view the working example here.

Post a Comment for "React.js "global" Component That Can Be Created Multiple Times"