by Sai gowtham

Dynamically render components in React

In this tutorial, we are going to learn about how to dynamically add or remove components 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;

Creating Dynamic component

Now, we need to create a dynamic component that helps us 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, we first imported two components (UserA, UserB) then we added it to the components object.

Inside the DynamicComponent we created a SelectUser variable and returned it, so that if we pass usera as a prop UserA component is rendered or 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 clicking on the buttons.

react dynamic component example

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course