Imagine you’re working on creating a new React-Bootstrap page and realize you need to use a component that’s slightly different from an existing component. There are a few different ways this could be done.

Depending on the context, the existing component could be parameterized to support the new functionality. This works in some scenarios, but it can often lead to components with many mismatched features that are difficult to maintain. Another option is to simply copy and paste the existing component. If the shared functionality is only going to be duplicated in two components, this might make sense. This isn’t a great solution if the functionality is going to be duplicated in three or more components though.

This is where dynamically generated components come in. Since React allows you to use simple functions as components and JavaScript supports first-class functions, a function can be created which dynamically generates new components.

In this example, the React-Bootstrap element will be used.

  
import React from 'react';
import Toast from 'react-bootstrap/Toast';
import Container from 'react-bootstrap/Container';

function ErrorToast() {
  return (
    <Toast>
      <Toast.Header>Error</Toast.Header>
      <Toast.Body>Something went wrong.</Toast.Body>
    </Toast>
  );
}

export default function App() {
  return <Container>
    <ErrorToast />
  </Container>
}  
  

This new element will create a new React-Bootstrap element with a preset header and body. What if you wanted to create a or a ? Ideally you wouldn’t need to duplicate the entire component just to modify the preset text.

#react #bootstrap

Dynamically Generating React-Bootstrap Components
7.30 GEEK