I am new to react js, so kindly pardon my lack of knowledge on the subject here. I did try googling and checking the "html-react-parser" page for any hints pertaining on the usage with navlink, but no luck there.
I have a simple react js application, wherein I am calling ajax via fetch from one of the component
getDataFromApi = () => {
Promise.all([
fetch("http://localhost/sample/superadmin/callA.json").then((response) => response.json())
])
.then(([sidemenu]) => {
this.setState({ sidemenu: sidemenu });
})
.catch((err) => {
console.log(err);
});
};
componentDidMount() {
this.getDataFromApi();
}
And grabbing the output of fetch and using it construct a variable with HTML string
var sidemenu = "";
const sidemenuJSON = this.state.sidemenu;
Object.keys(sidemenuJSON).forEach(function(key, val) {
if(key == "Dashboard") {
sidemenu += "<li className='nav-item d-flex align-items-center'><NavLink className='nav-link fs-7 py-sm-2 "+key.toLowerCase()+"-navitem fc-light' to='/' ><span>"+key+"</span></NavLink></li>";
}
else {
sidemenu += "<li className='nav-item d-flex align-items-center'><NavLink className='nav-link fs-7 py-sm-2 "+key.toLowerCase()+"-navitem fc-light' to='/"+key.toLowerCase()+"' ><span>"+key+"</span></NavLink></li>";
}
});
and then rendering the HTML by passing it to html-react-parser parse function
{parse(sidemenu)}
The looks and feel seems to be fine at first glance, but the navlink is broken as it is not clickable anymore. Any idea on this?
React
.jsfunction SideMenusList(props) {
const sidemenuJSON = props.sidemenu;
// use NavLink as a component ✅
const sideMenus = Object.keys(sidemenuJSON).map((key, index) => {
if(key === "Dashboard") {
return (
<li className='nav-item d-flex align-items-center' key={key.toString() + index}>
<NavLink className={'nav-link fs-7 py-sm-2' + key.toLowerCase() + '-navitem fc-light'} to='/' >
<span>{key}</span>
</NavLink>
</li>
)
} else {
return (
<li className='nav-item d-flex align-items-center'>
<NavLink className={'nav-link fs-7 py-sm-2' + key.toLowerCase() + '-navitem fc-light'} to={'/' + key.toLowerCase()} >
<span>{key}</span>
</NavLink>
</li>
)
}
});
return (
<ul>{sideMenus}</ul>
);
}
You can learn more from the official docs.