Welcome folks today in this blog post we will be building a dynamic select dropdown
from jsonplaceholder api
using axios
library in Javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
project using the below command
npx create-react-app sampleapp
npm i react-select
npm i axios
And after that you need to copy paste the code inside the App.js
file as shown below
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import React, { Component } from 'react' import Select from 'react-select' import axios from 'axios' export default class App extends Component { constructor(props){ super(props) this.state = { selectOptions : [], id: "", name: '' } } async getOptions(){ const res = await axios.get('https://jsonplaceholder.typicode.com/users') const data = res.data const options = data.map(d => ({ "value" : d.id, "label" : d.name })) this.setState({selectOptions: options}) } handleChange(e){ this.setState({id:e.value, name:e.label}) } componentDidMount(){ this.getOptions() } render() { console.log(this.state.selectOptions) return ( <div> <Select options={this.state.selectOptions} onChange={this.handleChange.bind(this)} /> <p>You have selected <strong>{this.state.name}</strong> whose id is <strong>{this.state.id}</strong></p> </div> ) } } |
As you can see we have the select dropdown
in which we are fetching the random list of items
from the jsonplaceholder
api using the axios
library. And also we are rendering the select dropdown
using the react-select library.
And also we have attached the onChange
event handler to the select dropdown and we are printing the id
of the selected element in the dropdown as shown below