first let me say that I'm not a TS developer. So if I make a dumb question, let me know.
I'm trying to use multiple select, basically I need multiple dropdown menus.
Started with the simple select from material-ui and I tried to develop forward.
I make it work with a single select, my problem is with that I don't understand how to add a new select using the onChange event
type OnChangeValue = {
locationNaming: unknown;
};
interface ServerNamingDropdownProps {
onChange(value: OnChangeValue): void;
error?: boolean | undefined;
initialValue?: string | undefined;
}
export const ServerNamingDropdown: React.FC<ServerNamingDropdownProps> = ({
onChange,
error,
initialValue = undefined,
}) => {
const [locationNamingSelected, setLocationNaming] = useState(
initialValue ? initialValue : '',
);
return (
<div>
<FormControl sx={{ minWidth: 120 }}>
<InputLabel id="demo-simple-select-label">Location</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={locationNamingSelected || ''}
label="Location"
error={error}
labelWidth={140}
style={{ width: 300 }}
onChange={e => {
onChange({
locationNaming: e.target.value,
});
setLocationNaming(e.target.value as string);
}} >
{location.map(item => (
<MenuItem value={item.abbreviation} key={item.key}>
{item.name}
</MenuItem>
))}
</Select>
</div>
);
};
I have to add a new dropdown for Department.
I understand that should add to OnChangeValue the departmentNaming.
But I don't understand how to manage the onChange.
Any idea would be greatly appreciated.
Thanks
React will re-run your render when you change your state, i.e. when you call setLocationNaming. The output of the render function should be different at that point. As @mstephen19 said, what your function returns can be conditional on the props or state. Here's a very simple (untested) sketch:
const MyConditionalRender = () => {
const [showMoreContent, setShowMoreContent] = useState(false);
return (
<div>
<button onClick={() => setShowMoreContent(true)}>Show</button>
{showMoreContent && (
<p>More Content, like an extra dropdown for the department.</p>
)}
</div>
);
};
Do read the Conditional Rendering docs that mstephen19 linked.