How to create dynamic component in the reactjs
How
to use the dynamic component in react js?
Dynamic
component or dynamically element we can create in react first
need you will start new project Or if you have already project then go to in
your “project > src folder”.
Then
create a folder as name components also, you can create a file
as navlist.js directly in the src folder. You
can create filename as you wish. As below code with screenshot:
import React from 'react';
const Navlinks = (props) => {
return(
<li><a href={props.linkss}>{props.linkName}</a></li>
)
}
export default Navlinks;
Now
you will create new file header.js Or as your requirement. Now
import new component in this file and create new component Header and
then you will write your JSON object in the state section.
Create a function readerList Or as you want.
How to render any dynamic code in the react?
After creating component then need to render code most important thing that must use curly braces {} and then you will use your
function with this keyword because you are accessing with the self code as: {this.readerList()}
import React,{Component} from 'react';
import Navlinks from './navlist';
export default class Header extends Component{
state = {
navlistss: [
{name:'Home', href:'index.html'},
{name:'About', href:'about.html'},
{name:'Services', href:'services.html'},
{name:'Contact', href:'contact.html'}
]
}
readerList = () => {
return this.state.navlistss.map(item => <Navlinks linkName={item.name} linkss={item.href} />);
}
render(){
return(
<div>
<ul>
{this.readerList()}
</ul>
</div>
);
}
Then go to your app.js file and call to Header component as given
code and screenshot below:
import React from 'react';
import './App.css';
import Header from './components/header/header';
function App() {
return (
<main>
<header>
<div className="container"><Header /></div>
</header>
</main>
);
}
After then you will run your npm server and go
to the browser, you will get your dynamic navigation as you defined in the state
as JSON file.
Also, we can create dynamic rendering with multiple objects using with one method as given below code:
Also, we can create dynamic rendering with multiple objects using with one method as given below code:
Componentfile.js
import React from 'react'
export default (props) => <div className={props.cls}><img src={props.mysrc} alt={props.alt} /></div>
pagefile.js
export default () => {
const textDetails = {
animals:[
{cls:'xyz', mysrc:'./xyz1.png', alt:'Xyz'},
{cls:'abc', mysrc:'./abc2.png', alt:'Abc'},
{cls:'cda', mysrc:'./cda.png', alt:'Cda'}
],
dogs:[
{cls:'dogs1', mysrc:'./puppy.png', alt:'Dog'},
{cls:'dogs2', mysrc:'./puppyNew.png', alt:'Puppy'}
]
}
const rendertextDetails = (items) => {
return items.map(item => <BannerImages cls={item.cls} mysrc={images(item.mysrc)} alt={item.alt} />)
}
return(
<>
{ rendertextDetails(textDetails.animals)}
{ rendertextDetails(textDetails.dogs)}
</>
)
}
No comments:
Note: Only a member of this blog may post a comment.