How to dynamically add component in reactjs?
One of the most important feature of Reactjs is its modularity. To make code more readable and maintainable, we break it into reusable components. And most of the times we need to dynamically add these components into scripts.
First of all let’s understand the difference between static component and dynamic component. Static components are included at the compile time while dynamic components are included at run time.
You can see that adding a dynamic component is a two way process. First we import it using React.lazy(). Then we wrap it in a wrapper component, Suspense. It has one prop, fallback, which renders anything inside it till DynamicComponentis loading.
App.js file is displayed below:
1
2 import "./styles.css";
3import React from "react"
4const DynamicComponent = React.lazy(() => import("./Dynamic"));
5
6export default class App extends React.Component {
7 constructor(props)
8 {super(props)
9 this.state={
10 Comp:false
11 }
12
13 };
14 render() {
15 return <><button onClick={() => this.setState({ Comp:true})}>
16 Preview Dynamic Component
17 </button>
18 {this.state.Comp ? (
19 <React.Suspense fallback={<div>Loading Component....</div>}>
20 <DynamicComponent />
21 </React.Suspense>
22 ) : null}</>;
23 }
24}
Dynamic.js file is displayed below
1import React from "react"
2export default class Dynamic extends React.Component {
3 constructor(props)
4 {
5 super(props)
6 this.state={
7 dialogues : [{
8 img:"https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/15/asset/buzzfeed-prod-fastlane-02/sub-buzz-15945-1491851513-1.jpg?downsize=700%3A%2A&output-quality=auto&output-format=auto",
9
10
11 }
12 ]
13 }
14
15 };
16 render() {
17 return this.state.dialogues.map((element, index) => {
18 return (
19 <div
20 key={index}
21 style={{ marginBottom: 20, border: "1px solid #000", padding: 5 }}
22 >
23 <img src={element.img} style={{ width: "100%", maxWidth: "400px" }} />
24 </div>
25 );
26 });
27 }
28}
Here is the link of live example which we done so far:
Click here
About
Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.
Follow him on TwitterHassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.
Follow him on TwitterTags
Click to see all tutorials tagged with: