简体   繁体   中英

How to update the option values in dropdown on child component from parent component state in react js?

I have a requirement like, In parent component i'm getting data from api and pass that array of data to DataTable child component to display in tablular format. In that, I need to display a drop-down for each column and option are predefined(No need of dynamic values). I need only, when the user select the dropdown values, it should update in parent component state and populates that selected in particular drop-down component.

Here is what i tried,

Parent component for storing dropdown values ::

   let [schema, setSchema] = useState([])

      const handleChange = (event, index) => {
        setSchema([
          ...schema,
          {
            Name: event.target.name,
            Type: event.target.value
          }
        ]);
    };

DataTable component inside parent compoent to display data ::

                <Container>
                    <DataTable
                        data={data}
                        meta_data={meta_data}
                        handleChange={handleChange}
                        schema={schema}
                    />
                </Container>

Here the iteration of each object from array to display dropdown once ::

 {
                Object.keys(filteredData[0]).map((field, index) => {
                  return (
                     <> 
                       <TableCell align="left" key={field} className={classes.headings}>
                         <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                            <FormControl className={classes.margin}>
                                <NativeSelect
                                  id="demo-customized-select-native"
                                  input={<BootstrapInput />}
                                  onChange={(e) => props.handleChange(e, index)}
                                  name={field}
                                  value={props.schema.length > 0 ? props.schema[index]['Type'] : null}
                                > 
                                  <option value={0}>Type</option>
                                  <option value={`str`}>string</option>
                                  <option value={`int`}>interger</option>
                                  <option value={`float`}>float</option>
                                </NativeSelect>
                            </FormControl>
                        </div>
                      </TableCell>
                     </>
                  ) 
                  }
                )}

I want, In the value prop of NativeSelect to populate the value of schema,

The schema should looks like

[
  {
    Name: 'passegner',
    Type: 'str'
  },
  {
    Name: 'Month',
    Type: 'float'
  },
]

When i retrieving the Type field of that array based in Index. It is giving 'Type' of undefined, But i actually working when console from outside of return in child component.

value={props.schema.length > 0 ? props.schema[index]['Type'] : null}  - > this line giving me the error and wroking fine when console.log() outside return.



console.log(props.schema.length > 0 ? props.schema[0]['Type'])  -> it is working

How to resolve?

Any suggestions would be great.

Above the return statement put a console like

console.log(props.schema[index]['Type'])

Try to figure out what went wrong, From my Guess Object.keys(filteredData[0]) may have move array values compared to props.schema[index] . So It may throw an error.

The useState hook has the following form:

const [state, setState] = useState(initialState);

In the React docs it is written:

If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.

Meaning that you should change this:

setSchema([
      ...schema,
      {
        Name: event.target.name,
        Type: event.target.value
      }
    ]);

into this:

setSchema((prevSchema) => {
  return [
      ...prevSchema,
      {
        Name: event.target.name,
        Type: event.target.value
      }
    ])
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM