How setting component dynamically by clicking a button. (React)

604 Views Asked by At

I want to display a component dynamically as I click different buttons from the menu. For example, my menu bar has Menu with buttons on the left and corresponding component on the right.

Menu Example Picture

When I click the button, it sets the name of the button as a state and uses this state to call the corresponding component. Below is my code. I want to get rid of "const dynamicComponent function" and use something simpler to call the component with the String.

For example, if I click displayNone Button and set the state of DisplayNone. I want to use this to call without having a separate function. This should work for all different buttons. Is there a way to do this?

Code for APP

import {
  Sidebar,
  SidebarDemo,
  DisplayNone,
  Gsap,
  GsapScrollMagic,
  GoogleMaps,
  ClipImage,
  LinearGradient,
  ButtonActive,
  ExportFunction,
  Axios,
  Telephone,
  MailTo,
  InputSearch,
  MapFilter,
  ColumnSize,
} from "./components";

function App() {
  const [comp, setComp] = useState("");

  const handleClick = (name) => {
    setComp(name);
  };

  const dynamicComponent = () => {
    switch (comp) {
      case "DisplayNone":
        return <DisplayNone />;
      case "Gsap":
        return <Gsap />;
      case "Gsap & ScrollMagic":
        return <GsapScrollMagic />;
      case "GoogleMaps":
        return <GoogleMaps />;
      case "Clip Image":
        return <ClipImage />;
      case "Linear Gradient":
        return <LinearGradient />;
      case "Button Active":
        return <ButtonActive />;
      case "Sidebar":
        return <Sidebar />;
      case "Export Function":
        return <ExportFunction />;
      case "Axios":
        return <Axios />;
      case "Telephone":
        return <Telephone />;
      case "Mail To":
        return <MailTo />;
      case "Input Search":
        return <InputSearch />;
      case "Map & Filter & Sort & Clone":
        return <MapFilter />;
      case "Column Size":
        return <ColumnSize />;
      default:
        return <Axios />;
    }
  };

  return (
    <div className="App">
      <Container fluid className="no-padding">
        <Row>
          <Col xs={3}>
            <SidebarDemo handleClick={handleClick} />
          </Col>
          <Col className="comp no-padding">{dynamicComponent()}</Col>
        </Row>
      </Container>
    </div>
  );
}

Code for sidebar

import React, { useState } from "react";
import Data from "../../Data.json";

const SidebarDemo = ({ handleClick }) => {
  const [clickedName, setClickedName] = useState("");
  const [query, setQuery] = useState("");

  const makeActive = (name) => {
    handleClick(name);
    setClickedName(name);
  };

  const modifiedData = Data.filter((item) => {
    return item.toLowerCase().includes(query.toLowerCase()) ? item : null;
  });

  const sortedData = modifiedData.sort((a, b) => a.localeCompare(b));

  return (
    <div className="flex-column align-items-center sidebar">
      <br />
      <h4>Damon's Library</h4>
      <br />
      <input
        type="text"
        placeholder="Search.."
        className="sidebar-input-box"
        onChange={(e) => setQuery(e.target.value)}
        value={query}
      />
      <br />
      <div className="mr-auto flex-column button-bar">
        {sortedData.map((data, i) => (
          <span
            className={"sidebar-button" + (data === clickedName ? " button-active" : "")}
            key={i}
            onClick={() => makeActive(data)}>
            {data}
          </span>
        ))}
      </div>
    </div>
  );
};

export default SidebarDemo;

Data.json contains [Item1, Item2, Item3, ...]

1

There are 1 best solutions below

1
DedaDev On

One workaround can be this,

1st import all components (not-destructuring)

import * as AllComponents from "./components";

Then create a new variable that extracts exact component with a dynamic name,

const DynamicComponent = AllComponents[comp]

and then render that Dynamic component

<DynamicComponent />