Michelle Michelle -4 years ago 45
React JSX Question

Set ReactJS results in a additional div, new component?

This is the code my react component:

class App extends React.Component {

constructor() {
super();
}

update(e) {
axios.get('https://myjsonurl.com', {
params: {
phrase: e.target.value
}
}).then(function (response) {

console.log(response.data);

}).catch(function (err) {
console.log(err);
});
}

render() {
return (
<div>
<input type="text" onChange={this.update} />
</div>
)
}
}


By searching I get correct results in console of my browser. Can someone give me some tipps how can I insert this data in a list?

Is there to create a new component and tell in response to use this component?

Answer Source

Create a state variable and save the response inside that. Call a function from render method that will create the list from that response.

Bind the update method inside constructor.

Like this:

class App extends React.Component {

    constructor() {
        super();
        this.state = {
            data: []
        }
        this.update = this.update.bind(this);   //bind the method
    }

    update(e) {
        axios.get('https://myjsonurl.com', {
            params: {
                phrase: e.target.value
            }
        }).then((response) => {
            this.setState({data: response.data});   //set the response in state
        }).catch((err) => {
            console.log(err);
        });
    }

    createList(){
        if(!this.state.data.length) return null;

        return  <ul>
                    {this.state.data.map((el, index) => <li key={index}> {el.KeyName} </li>)}
                </ul>
    }

    render() {
        return (
            <div>
                <input type="text" onChange={this.update} />
                {this.createList()}
            </div>
        )
    }
}

Note: Replace el.KeyName with actual key that you want to show, and assign some unique value to key key={index} i used index because don't know the details about the response.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download