javascript - How to parse result from backend to dropdown react axios? - Stack Overflow

I'm learning React, I made a page with Form. This Form should get data from back-end via axios.I

I'm learning React, I made a page with Form.

This Form should get data from back-end via axios. I need help because whatever I do, array doesn't display in the select options.

Example of data:

[{"country": "Germany" "code": 112 }]

import React, { Component } from 'react';
import { Row, Col, Button, Form } from 'react-bootstrap';
import axios from 'axios';

class Form extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            country: []

        };
    }
    ponentDidMount() {
        axios
            .get('URL')
            .then((response) => {
                console.log(response);

                this.setState({
                    country: response
                });
            })
            .catch((error) => console.log(error.response));
    }
    handleChangeCountry = (event) => {
        this.setState({ country: event.target.value });
    };

    inputCountryHandler = (event) => {
        this.setState({
            input: {
                country: event.target.value
            }
        });
    };

    render() {
        //  const { country} = this.state;

        return (
            <Form className="calculator-table">
                <Form.Group controlId="first-row" className="Focus-line">
                    <Form.Label>Country</Form.Label>
                    <Form.Control
                        as="select"
                        className="User-Input"
                        placeholder=""
                        value={this.state.country}
                        onChange={this.handleChangeCountry}
                        id="country"
                        option={this.country}
                    />
                </Form.Group>

        );
    }
}

export default Form;

I want the array data to be displayed in drop down select.

Thanks for any answer

I'm learning React, I made a page with Form.

This Form should get data from back-end via axios. I need help because whatever I do, array doesn't display in the select options.

Example of data:

[{"country": "Germany" "code": 112 }]

import React, { Component } from 'react';
import { Row, Col, Button, Form } from 'react-bootstrap';
import axios from 'axios';

class Form extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            country: []

        };
    }
    ponentDidMount() {
        axios
            .get('URL')
            .then((response) => {
                console.log(response);

                this.setState({
                    country: response
                });
            })
            .catch((error) => console.log(error.response));
    }
    handleChangeCountry = (event) => {
        this.setState({ country: event.target.value });
    };

    inputCountryHandler = (event) => {
        this.setState({
            input: {
                country: event.target.value
            }
        });
    };

    render() {
        //  const { country} = this.state;

        return (
            <Form className="calculator-table">
                <Form.Group controlId="first-row" className="Focus-line">
                    <Form.Label>Country</Form.Label>
                    <Form.Control
                        as="select"
                        className="User-Input"
                        placeholder=""
                        value={this.state.country}
                        onChange={this.handleChangeCountry}
                        id="country"
                        option={this.country}
                    />
                </Form.Group>

        );
    }
}

export default Form;

I want the array data to be displayed in drop down select.

Thanks for any answer

Share Improve this question asked Sep 3, 2019 at 4:21 NatNat 713 silver badges9 bronze badges 3
  • You will get the countries in response.data I guess. – Milind Agrawal Commented Sep 3, 2019 at 4:37
  • Check this - stackoverflow./questions/36205673/… – ravibagul91 Commented Sep 3, 2019 at 4:41
  • Hi Natalia, check my solution and let me know if that helps. – ravibagul91 Commented Sep 3, 2019 at 5:09
Add a ment  | 

4 Answers 4

Reset to default 2

You should first parse the JSON response from the API.

ponentDidMount() {
        axios
            .get('URL')
            .then((response) => {
                console.log(response);

                this.setState({
                    country: JSON.parse(response) //parse the response
                });
            })
            .catch((error) => console.log(error.response));
    }

As per the docs, Form.Control don't accept option as props.

You must iterate your country array to get the options.


<Form.Control
    as = "select"
    className = "User-Input"
    placeholder = ""
    value = { this.state.selectedCountry }
    onChange = { this.handleChangeCountry }
    id = "country"  //Remove this id, otherwise you will get the warning
> 
    {
        this.state.country && this.state.country.length > 0 && this.state.country.map(countryItem => <option key={countryItem.country}>{countryItem.country}</option>)
    } 
</Form.Control>

You should have a separate state variable to store the selected value,

constructor(props) {
    super(props);
    this.state = {
       country: [],
       selectedCountry: ''  //add this to store selected country value
    };
}

And your handleChangeCountry function should be,

handleChangeCountry = (event) => {
    this.setState({ selectedCountry: event.target.value });
};

Note: axios return response in JSON format, but the actual data is in response.data, so you should set your state as,

this.setState({
      country: response.data
});

When you specify id = 'country', you will get warning,

Warning: controlId is ignored on <FormControl> when id is specified.

You should remove the id = 'country'.

I believe the issue is that the Form.Control ponent as select expects options as children ponents. So you would need to map over the response array like so:

<Form.Control as="select">
    {this.state.country.map(response => {
        <option>{response.country}</option>
    })}
</Form.Control>

According to docs you must use array of option

<Form.Control
    as="select"
    className="User-Input"
    placeholder=""
    value={this.state.country}
    onChange={this.handleChangeCountry}
    id="country">
    {
        this.state.country.map((c, i) => <option value={c.code} key={i}>{c.country}</option>)
    }
</Form.Control>

Also, you have to use 2 state variables, example

this.state = {
    selectedCountries: [], // from select control
    country: []            // from backend
}

And populate select value from this.state.selectedCountries

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745125876a4612687.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信