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.
import React from "react";
function UserA() {
return (
<div>
<h1>This is user A</h1>
</div>
);
}
export default UserA;
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.
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.
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.