How can I duplicate menuItems as much as data from rails server

Viewed 43

I know I can use MenuItem like this.

            <FormControl fullWidth>
              <InputLabel>Job area</InputLabel>
              <Select
                autoFocus
                label="job_area"
                sx={{
                  width: "70%",
                }}
                inputProps={{
                  name: "max-width",
                  id: "max-width",
                }}
              >
                <MenuItem value={false as any}>false</MenuItem>
              </Select>
            </FormControl>

How about if I want to get data from rails server?
I try to search it, but I couldn't reach..

Duplicating data as mush as data manually is ludicrous.
How can I Duplicate like using function?

Thank you.

Addition(Solved)


I tried:

...
                {props.jobArea.map((jobArea: any) => {
                  <MenuItem value={jobArea.name as string}>
                    {jobArea.name}
                  </MenuItem>;
                })}
              </Select>
            </FormControl>

console.log is:

{$$typeof: Symbol(react.element), type: {…}, key: null, ref: null, props: {…}, …}
$$typeof: Symbol(react.element)
key: null
props: {value: '関西', children: '関西'} <--- here is jobArea.name
ref: null
type: {$$typeof: Symbol(react.forward_ref), propTypes: {…}, render: ƒ}
_owner: FiberNode {tag: 0, key: null, stateNode: null, elementType: ƒ, type: ƒ, …}
_store: {validated: false}
_self: undefined
_source: {fileName: '/Users/daimetatsuru/staging-at-engineer_rails/frontend/src/components/UsersSearch.tsx', lineNumber: 218, columnNumber: 23}
[[Prototype]]: Object

I think that's fine.
What's wrong...

I got this error:

SelectInput.js:423 MUI: You have provided an out-of-range value `undefined` for the select (name="max-width") component.
Consider providing a value that matches one of the available options or ''.
The available values are "".
1 Answers

Seems like you are using MUI

You component needs to make a request to some endpoint to get your options

const [options, setOptions] = useState([]);
useEffect(() => {
  async function loadOptions() {
     const response = await fetch('/options');
     const options = await response.json();
     setOptions(options);
  }
  loadOptions(); 
}, []) 

Then you can loop through the options fetched and render a MenuItem for each one that you got.

<FormControl fullWidth>
 <InputLabel>Job area</InputLabel>
 <Select
    autoFocus
    label="job_area"
    sx={{
      width: "70%",
    }}
    inputProps={{
     name: "max-width",
     id: "max-width",
    }}
  >
  {options.map((option, idx) => (
    <MenuItem 
     key={`option-${idx}`}
     value={option.id}
    >
     {option.label}
    </MenuItem> 
  )}
 </Select>
</FormControl>
Related