Search code examples
reactjsmaterial-uireact-props

Send multiple components with a singe props in React.js with Material UI


Is it any way I can send multiple <MenuItem> in one props using Material UI?

Form.js

export default function MyForm = (props) => {

<FormControl
        <Select value={ItemValue} >
          items={props.items}
        </Select>
</FormControl>

}

I have tried to output the props in a difference ways. Setting comma betweens <MenuItem> does only render the last <MenuItem>. Wrapping it with <React.Fragment> does work, but then the MenuItem value doesn't get picket up from value={ItemValue}

{ItemValue} here is just a function that pick up the MenuItem value on a event handling.

App.js

<MyForm
    items={
           <MenuItem value={1}>value 1</MenuItem>
           <MenuItem value={2}>value 2</MenuItem>
           <MenuItem value={3}>value 3</MenuItem>
           <MenuItem value={4}>value 4</MenuItem>
          }
/>

Is it any proper way to configure this?


Solution

  • The Easiest way to work this out is to pass the values as props into the MyForm as array of values, here is an illustrative example: App.js

    export default function App() {
    const myItemsValues = [1, 2, 3, 4];
    return (
        <div>
            <MyForm items={myItemsValues} />
        </div>
    );}
    

    MyForm.js

    export default function MyForm({ items }) {
    return (
        <div>
            <FormControl>
                <Select value={1}>
                    {items.map((value) => {
                        return <MenuItem value={value}>{value}</MenuItem>;
                    })}
                </Select>
            </FormControl>
        </div>
    );}
    

    If You Insist Of Passing Them As A Collection:

    export default function App() {
    const myItemsValues = [1, 2, 3, 4];
    const myItemsComponents = myItemsValues.map((value) => {
        return <MenuItem value={value}>{value}</MenuItem>;
    });
    return (
        <div>
            <MyForm items={myItemsComponents} />
        </div>
    );}
    export default function MyForm({ items }) {
    return (
        <div>
            <FormControl>
                <Select value={1}>{items}</Select>
            </FormControl>
        </div>
    );}
    

    it's basically the same,both will produce the same results.