reactjs – React.js – How to Render a Component Based on its Object Value?
I have multiple lists that I want to render by the same rules, except for the property ‘component’, where I need to render the component that is listed on each list:
const pokemon = [
{
"number": 1,
"name": "bulbasaur",
"url": "https://pokeapi.co/api/v2/pokemon/1/"
},
{
"number": 2,
"name": "ivysaur",
"url": "https://pokeapi.co/api/v2/pokemon/2/"
},
];
const pokemonConfig = [
{
title: 'pokedex #',
field: 'number'
},
{
title: 'name',
field: 'name',
component: PokemonName
}
];
<Grid config={pokemonConfig} data={pokemon} />
const Grid = ({ config, data }) => (
<table>
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
{config.map((c, i) => <th key={i}>{c.title}</th>)}
</tr>
{data.map((d, i) =>
<tr key={i}>{config.map((c, i) => c.hasOwnProperty('component') ?
// the component and its data here...
: <td key={i}>
{d[c.field]}
</td>)
}
</tr>)}
</tbody>
</table>
);
What is the best practice to do so?
Thanks much!!
Read more here: Source link