Dynamically render components in React

Dynamically render components in React

In this tutorial, we are going to learn about how to render components dynamically in react with the help of examples.

First, we need to create two new components so that we can use them for dynamic rendering.

userA.js
import React from "react";

function UserA() {
  return (
    <div>
      <h1>This is user A</h1>
    </div>
  );
}

export default UserA;
userB.js
import React from "react";

function UserA() {
  return (
    <div>
      <h1>This is user B</h1>
    </div>
  );
}

export default UserB;

Dynamic component

Now we need to create a dynamic component that helps to render the other components dynamically based on the props.

Dynamic.js
import React from "react";
import UserA from "./userA";
import UserB from "./userB";

const components = {
  usera: UserA,  userb: UserB};

function DynamicComponent(props) {
  const SelectUser = components[props.user];  return <SelectUser />;
}

export default DynamicComponent;

In the above code first, we imported two components then we added it to the components object.

Inside Dynamiccomponent we created a SelectUser variable and returned it, so that if we pass usera as a prop UserA component is rendered else if we pass userb as a prop UserB component is rendered on the screen.

Using Dynamic component

Let’s use our dynamic component now by importing it.

App.js
import React, { useState } from "react";
import DynamicComponent from "./Dynamic";

function App() {
  const [user, changeUser] = useState("usera");
  return (
    <div>
      {/* initially UserA component is rendered */}
      <DynamicComponent user={user} />      <button onClick={() => changeUser("usera")}>Switch user-a</button>      <button onClick={() => changeUser("userb")}>Switch user-b</button>    </div>
  );
}

export default App;

Here we are switching between two components dynamically by using buttons.

dynamic-component-example