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>
)
}
}
Well I have a react dropdown component
<Dropdown/>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<Dropdown items={pets} placeholder="Zoo world" />
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>
You can check the header value by using Array.map method and then return the desired output.
<div>
{pets.map((e) => {
if (e.header === "Woffy") {
return <Component1 />;
} else if (e.header === "kitty") {
return <Component2 />;
} else {
return null;
}
})}
</div>;