I would like to conditionally render a component based on the header property of my constant. Basically if the header is Woffy --> Render Component1 This is my code:
import React from 'react';
import Component1 from '../Collection/Component1';
import Component2 from '../Collection/Component2';
const pets = [
{
header: 'Woffy',
image: '/img/dog.png'
},
{
header: 'kitty',
image: '/img/cat.png'
},
class demo class extends React.Component{
render(){
return(
<div>
{header === "Woofy" && <Component1 />}
{header === "kitty" && <Component2 />}
</div>
)
}
}
CodePudding user response:
You can check the header
value by using arrray.map
and then return the desire output.
<div>
{
pets.map((e) => {
if (e.header === "Woffy") {
return <Component1 />
}else if(e.header === "kitty"){
return <Component2 />
}else{
return null;
}
})
}
</div>
CodePudding user response:
Well I have a react dropdown component from Fluent UI, I want to display the component based in the dropdown selection, wich I want to asign from the header property. is that possible ? This is my dropdown
you can use variable which you are as value
of the state of Dropdown and then compare the variable to render the component.
import React from "react";
import { Dropdown } from "@fluentui/react-northstar";
const pets = [
{
key: "1",
header: "Woffy",
image: "/img/dog.png"
},
{
key: "2",
header: "kitty",
image: "/img/cat.png"
}
];
const DropdownExample = () => {
const [dropdownValue, setDropdownValue] = React.useState("3");
console.log(dropdownValue);
return (
<Dropdown
items={pets}
value={dropdownValue}
onChange={(_, data) => setDropdownValue(data.value.header)}
/>
);
};
now compare this dropdownValue
variable to render component.
<div>
{dropdownValue === "Woofy" && <Component1 />}
{dropdownValue === "kitty" && <Component2 />}
</div>
please accept and upvote the answer