Inject toasts, modals, and more on the fly - all in React

Last update: Jul 30, 2022
description
Inject toasts, modals, and more on the fly - all in React!

react-node-inject

This is the official documentation for the react-node-inject package located here and the repository located here.

Installation

npm install react-node-inject
pnpm install react-node-inject

Features

  • Context Provider for injecting a ReactNode into the DOM.
  • Ability to remove (uninject) or purge nodes from the page via. an id parameter.

Example

_app.tsx

import { InjectProvider } from 'react-node-inject';

const App = () => {
  return (
    // This is the level at which injectables will be appended to the DOM.
    <InjectProvider>
      // The rest of the app.
      // May contain <MyReactComponent /> from below or something similar.
    </InjectProvider>
  );
}

export default App;

MyReactComponent.tsx

import { useInject } from 'react-node-inject';

const MyReactComponent = () => {
  { inject } = useInject();

  const handleClick = () => {
    inject(
      // An example of a modal with TailwindCSS
      // You can also inject a custom  component you have, etc.
      <div className='absolute min-h-screen flex items-center justify-center'>
        <div className='border bg-white shadow px-8 py-4'>
          This modal is injected when the button is clicked!
        </div>
      </div>
    );
  }

  return (
    <button onClick={handleClick}>Click me</button>
  )
}

export default MyReactComponent;

The Problem We're Solving

Instead of loading a modal with an empty state, you can "inject" components on the fly into the DOM. This way, the client isn't seeing any content they shouldn't to begin with and you can have multiple instances of modals, toasts, etc.

In other words, you'll never do this again:

BadModal.tsx

interface IBadModalProps {
  message: string;
}

// This is an example of what bad code looks like.
// Don't do this!
const BadModal = ({ message }: IBadModalProps) => {
  // Preventing the modal from showing if the message doesn't exist.
  if(message === '') {
    return null;
  }

  return (
    // The modal when a message exists.
  )
}

export default BadModal;

BadForm.tsx

import { Fragment } from 'react';

// This is an example of what bad code looks like.
// Don't do this!
const BadForm = () => {
  const [message, setMessage] = useState('');

  const handleClick = () => {
    setMessage('You clicked the button!')
  }

  return (
    <Fragment>
      {/* We're trying to avoid this: */}
      <BadModal message={message} />

      <button onClick={handleClick}>Submit</button>
    </Fragment>
  )
}

export default BadForm;

Instead, you can start doing this:

GoodModal.tsx

interface IGoodModalProps {
  message: string;
}

const GoodModal = ({ message }: IGoodModalProps) => {
  return (
    // The modal - the message is guarenteed to be here.
  )
}

export default GoodModal;

GoodForm.tsx

import { inject } from 'react-node-inject'

const GoodForm = () => {
  const handleClick = () => {
    // An example of when you can inject a modal.
    inject(<GoodModal message='You clicked the button!' />);
  }

  return (
    <button onClick={handleClick}>Submit</button>
  )
}

export default GoodForm;

Inject Context

interface IInjectContext {
  // Inject a ReactNode into the DOM with an optional id
  inject: (node: ReactNode, id?: string) => void;

  // If an injected ReactNode has an id, remove it from the DOM.
  uninject: (id: string) => void;

  // Purge all injected ReactNode components from the DOM.
  purge: () => void;

  // An array of injectables (contains id: string and node: ReactNode properties)
  injected: Injectable[];
}

Contributing

At the moment, this repository is maintained by a student at Iowa State University. If you'd like to contribute, please fork this repository, make your changes, and then send in a pull request. Please respect the current .prettierrc configuration - thank you!

GitHub

https://github.com/ryanhaticus/react-node-inject
You might also like...

"Math magicians" is a website for all fans of mathematics.

"Math magicians" is a website for all fans of mathematics. It allows users to make simple calculations and read a random math-releted quote.

Mar 29, 2022

An all in one preset for writing Preact apps with the vite bundler.

@preact/preset-vite An all in one preset for writing Preact apps with the vite bundler. Features: Sets up Hot Module Replacement via prefresh Enables

Aug 2, 2022

A javascript microframework to shorten daily use CSS class manipulator methods by adding them all into a single method

CSS Class Builder A small typescript package built to work with ReactJS to short

Jan 7, 2022

Repository responsible for all code developed during the JavaScript Beginners Series

Série de Vídeos para Iniciantes em JavaScript Uma série de vídeos ensinando conc

Aug 2, 2022

💥 The best all-in-one toolbox. Bazinga!

💥 The best all-in-one toolbox. Bazinga!

Jul 20, 2022

A React JS project to make age and gender prediction using Agify.io and Genderize.io. Only for practice use and just for fun~

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 29, 2022

Responsive and customizable search and select for Giphy's GIFs and Stickers.

Responsive and customizable search and select for Giphy's GIFs and Stickers.

Responsive and customizable search and select for Giphy's GIFs. https://sergiop.github.io/react-giphy-searchbox/ React Giphy Searchbox is a powerful r

Jun 20, 2022

HTML meta tags for React-based apps. Works for both client- and server-side rendering, and has a strict but flexible API.

React Document Meta HTML meta tags for React-based apps. Works for both client- and server-side rendering, and has a strict but flexible API. Built wi

Jun 14, 2022

An interactive CLI automation tool 🛠️ for creating react.js and next.js projects most fast and efficiently. ⚛️

An interactive CLI automation tool 🛠️ for creating react.js and next.js projects most fast and efficiently. ⚛️

An interactive CLI automation tool 🛠️ for creating react.js and next.js projects most fast and efficiently. ⚛️

Apr 12, 2022
🎯 React component for transportation of modals, lightboxes, loading bars... to document.body or else.

React-portal Struggling with modals, lightboxes or loading bars in React? React-portal creates a new top-level React tree and injects its children int

Aug 1, 2022
Creating modals in React Framer Motion

Creating modals in React Framer Motion

Jul 21, 2022
A starter for React with Typescript with the fast Vite and all static code testing with Eslint and formatting with Prettier.
A starter for React with Typescript with the fast Vite and all static code testing with Eslint and formatting with Prettier.

A starter for React with Typescript with the fast Vite and all static code testing with Eslint and formatting with Prettier.

Aug 4, 2022
✨ View all of your GitHub stats and compare your stats with friends, made using nextjs and tailwind.

✨ View all of your GitHub stats and compare your stats with friends, made using nextjs and tailwind.

Jun 22, 2022
Write components once, run everywhere. Compiles to Vue, React, Solid, Angular, Svelte, and more.
Write components once, run everywhere. Compiles to Vue, React, Solid, Angular, Svelte, and more.

Write components once, run everywhere. Compiles to: At a glance Mitosis is inspired by many modern frameworks. You'll see components look like React c

Aug 1, 2022
This project is collection of large projects's source code (codebases), built with Reactjs. Eg: Bestbuy, Postman, Trello, Udacity, Coursera, Skillshare, Invision, Intercom, Pipedrive, ... and more.
This project is collection of large projects's source code (codebases), built with Reactjs. Eg: Bestbuy, Postman, Trello, Udacity, Coursera, Skillshare, Invision, Intercom, Pipedrive, ... and more.

This project is collection of large projects's source code (codebases), built with Reactjs. Eg: Bestbuy, Postman, Trello, Udacity, Coursera, Skillshare, Invision, Intercom, Pipedrive, ... and more.

Aug 5, 2022
A website for browsing ECMAScript proposals/champions/specs and more.
A website for browsing ECMAScript proposals/champions/specs and more.

proposals.es A website for keeping up to date with ECMAScript proposals. Created with React, TypeScript, and Next.js. Developing Setup Clone this repo

Aug 1, 2022
Hypersearch enhances all major search engines (Google, DuckDuckGo, Amazon, etc.) with results from trusted sources in the sidebar and removing results from blocked sources
Hypersearch enhances all major search engines (Google, DuckDuckGo, Amazon, etc.) with results from trusted sources in the sidebar and removing results from blocked sources

Hypersearch Coming soon for Firefox and Opera. Microsoft Edge users can install from the Chrome store. Hypersearch enhances all major search engines (

Aug 2, 2022
React Translator is a Web Interface created for make the creation of locales.json more easier.

React Translator is a Web Interface created for make the creation of locales.json more easier. Theses locales files can be used in the package @oneforx/react-translator

May 27, 2022
Description So you want to make a difference in the world. You definitely want to do more than just sign a petition
Description So you want to make a difference in the world. You definitely want to do more than just sign a petition

peticipate Description So you want to make a difference in the world. You definitely want to do more than just sign a petition. You have some awesome

Dec 7, 2021