I am pretty new to web development, I want to be able to retrieve the value in the select that is selected in the below code, but I am unable to.
I want to get it in a variable in order to send it using api. I am able to open the dropdown meni and able to
import {useHistory} from 'react-router-dom'
import { useForm, FormActions } from '../../context/FormContext'
import { Theme } from '../../components/Theme/intex'
import { ChangeEvent, useEffect } from 'react'
export const FormStep1 = () => {
const history = useHistory()
const { state, dispatch} = useForm()
const handleNameChange = (e: ChangeEvent<HTMLInputElement>) => {
dispatch({
type: FormActions.setName,
payload: e.target.value
})
}
const handleNextStep = () =>{
if(state.name !== '') {
history.push('/step2')
} else{
alert('Please enter your details')
}
state.team = 'test'
}
useEffect(()=>{
dispatch({
type: FormActions.setCurrentStep,
payload: 1
})
},[])
return(
<Theme>
<C.Container>
<p className='Step'>Step 1/3</p>
<h2>Team Name</h2>
<p>Select Existing Team or Create a New Team</p>
<label> Select your team_usecase </label>
<select name="pets" id="pet-select">
<option value=""> Select your team </option>
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="hamster">hamster</option>
<option value="parrot">parrot</option>
<option value="spider">spider</option>
<option value="goldfish">Goldfish</option>
</select>
)
}```
I was able to find a few solutions but I couldn't get them to work, so any help would be appreciated.
You can achieve this by putting onChange handler on select like this:
return(
<Theme>
<C.Container>
<p className='Step'>Step 1/3</p>
<h2>Team Name</h2>
<p>Select Existing Team or Create a New Team</p>
<label> Select your team_usecase </label>
<select name="pets" id="pet-select" onChange=(e => handleNameChange(e))>
<option value=""> Select your team </option>
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="hamster">hamster</option>
<option value="parrot">parrot</option>
<option value="spider">spider</option>
<option value="goldfish">Goldfish</option>
</select>
</C.Container>
</Theme>
)
Related
i have two product cards each have it's own category like color,size,etc and each have add to cart button. im using useRef() hook to get the selected category by user. and console it, when i click add to cart button.the problem is im only getting the second product category selected by the user whenever i press both buttons. please do check the code below.feel free to ask for any clarification.
import "./Card.css";
import { useRef } from "react";
function Card() {
const colorRef = useRef();
const quantityRef = useRef();
const sizeRef = useRef();
const submitHandler = (event) => {
event.preventDefault();
const selectedColor = colorRef.current.value;
const selectedQuantity = quantityRef.current.value;
const selectedSize = sizeRef.current.value;
const selectedData = {
color: selectedColor,
quantity: selectedQuantity,
size: selectedSize
};
console.log(selectedData);
};
return (
<div className="main-container">
<div className="container">
<div className="image-container">
<img
src="https://images.pexels.com/photos/9558601/pexels-photo-9558601.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
</div>
<h2> T-Shirt </h2>
</div>
<form className="form-conatiner" onSubmit={submitHandler}>
<div className="selectors">
<p>Solid Round Neck T-shirt</p>
<select id="color" ref={colorRef} name="color" required>
<option>Color</option>
<option value="black">Black</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
</select>
<select ref={quantityRef} name="qantity" required>
<option>Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select ref={sizeRef} name="size" required>
<option>Size</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="small">Small</option>
</select>
<div>
<button>Add to Cart</button>
</div>
</div>
</form>
<div className="container">
<div className="image-container">
<img
src="https://images.pexels.com/photos/440320/pexels-photo-440320.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
</div>
<h2> i-Watch </h2>
</div>
<div className="form-conatiner">
<div className="selectors">
<p>Dizo watch with amlod </p>
<select id="2" ref={colorRef} name="color" required>
<option>Brand</option>
<option value="Apple">Apple</option>
<option value="Samsung">Samsung</option>
<option value="Pixel">Pixel</option>
</select>
<select ref={quantityRef} name="qantity" required>
<option>Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select ref={sizeRef} name="size" required>
<option>size </option>
<option value="29mm">29mm</option>
<option value="34mm">34mm</option>
<option value="42mm">42mm</option>
</select>
<div>
<button onClick={submitHandler}>Add to Cart</button>
</div>
</div>
</div>
</div>
);
}
export default Card;
You are using same ref with different elements,so it will have reference to last element,to which it is passed, That's why you always get second product's references
You should try using ref array like this
const colorRef = useRef([]);
const quantityRef = useRef([]);
const sizeRef = useRef([]);
and pass it this way (here is for one product)
<select id="color" ref={(el)=>{colorRef.current.push(el)}} name="color" required>
<option>Color</option>
<option value="black">Black</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
</select>
<select ref={(el)=>{quantityRef.current.push(el)}} name="qantity" required>
<option>Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select ref={(el)=>{sizeRef.current.push(el)}} name="size" required>
<option>Size</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="small">Small</option>
</select>
and then use it like this way in you submit handler
const submitHandler = (event) => {
event.preventDefault();
const selectedColor1 = colorRef.current[0].value;
const selectedColor2 = colorRef.current[1].value;
const selectedQuantity1 = quantityRef.current[0].value;
const selectedQuantity2 = quantityRef.current[1].value;
const selectedSize1 = sizeRef.current[0].value;
const selectedSize2 = sizeRef.current[1].value;
const selectedData1 = {
color: selectedColor1,
quantity: selectedQuantity1,
size: selectedSize1
};
const selectedData2 = {
color: selectedColor2,
quantity: selectedQuantity2,
size: selectedSize2
};
console.log(selectedData1);
console.log(selectedData2);
};
A working codesandbox is here.
A good and sort read Here. Hope this will help.
That is an expected behaviour. The ref is going to be assigned to the first element and then to the second one. That is why you're getting always the last.
Second one, you're wrapping only one element with the form tag.
For this you should use useState hook and the onChange for the inputs. Let's say:
function Card() {
const [firstElement, setFirstElement] = useState({})
const [secondElement, setSecondElement] = useState({})
const handleFirstElementChange = (key, event) => {
setFirstElement((oldState) => ({ ...oldState, [key]: event.target.value }))
}
const submitHandler = (event) => {
event.preventDefault();
console.log(firstElement, secondElement);
};
return <>
<h2>T-shirt</h2>
<select id="color" required onChange={(event) => handleFirstElementChange('color', event)>
<option>Pick a color</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Ref</option>
</select>
</>
}
delcare state object
const [addEmpData, setAddEmpData] = useState({
user_id:'',employee_id:'',name:'',date_of_join:'',gender:'',designation:'',user_role:''
})
here added value prop in select tag as addempData.gender.
and a onchange fn that set the value to state.
<div className="col-sm-6">
<div className="form-group">
<label className="col-form-label">Gender</label>
<select value={addEmpData.gender} onChange={(e)=>setAddEmpData({...addEmpData,gender:e.target.value})} className="select">
<option value='select'>Select</option>
<option value="Male">Male</option>
<option value='Female'>Female</option>
</select>
</div>
</div>
The proper implementation of controlled components in React base on your use case.
import { useState } from "react";
export default function App() {
const [addEmpData, setAddEmpData] = useState({
user_id: "",
employee_id: "",
name: "",
date_of_join: "",
gender: "",
designation: "",
user_role: ""
});
console.log(addEmpData);
return (
<div className="col-sm-6">
<div className="form-group">
<label className="col-form-label">Gender</label>
<select
value={addEmpData.gender}
onChange={(e) =>
setAddEmpData((prev) => ({ ...prev, gender: e.target.value }))
}
className="select"
>
<option value="select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
);
}
You may also interact the demo in the CodeSandbox just click here
const [addEmpData, setAddEmpData] = useState({user_id:'',employee_id:'',name:'',date_of_join:'',gender:'',designation:'',user_role:''})
function handler(e)
{
const {name,value}=e.target;
setAddEmpData({
...addEmpData,
[name]:value
})
}
<div className="form-group">
<label className="col-form-label">Gender : </label>
<select value={addEmpData.gender} onChange={(e)=>handler(e)} name="gender" className="select">
<option value='select'>Select</option>
<option value="Male">Male</option>
<option value='Female'>Female</option>
</select>
</div>
You can try this code .
In this value will be read and changed in the state too
To try this code check this
The Problem
Using the current state in the setState is an anti-pattern in React.js.
The Solution
Use the prevState inside your setState to destructuring the unchanged properties:
onChange={
(e) => setAddEmpData((prevState) => {...prevState, gender:e.target.value})
}
Disclaimer
You can use any name instead of prevState but it must be the same on the left side and right side. prevState is just a paramere name but considered as a best practice to demonstrate the purpose of setState with the restructuring previous state.
I have 3 selection boxes which called paymentStatus, orderStatus, deliveryStatus and those will update my database with values in options. In my code I cannot update my database without selecting values from all 3 selection box.If I select value from paymentStatus only it wont update my database. What I need is to update my database only from selection boxes what I changed.It may be 1 or 2 or all of them.
const [pStatus, setPStatus] = useState('');
const [oStatus, setOStatus] = useState('');
const [dStatus, setDStatus] = useState('');
const updateOrderHandler = (e) => {
alert("Update handler working and passing data");
const adminOrderUpdate = {
'paymentInfo.paymentStatus':pStatus,
'orderStatus':oStatus,
'deliveryInfo.deliveryStatus':dStatus
}
dispatch(adminUpdateOrder(orderId, adminOrderUpdate))
}
<form>
<p className="ststxt">Payment Status</p>
<div className="statSel">
<select name="PS" onChange={(e) => setPStatus(e.target.value)} id="format">
<option selected disabled >{paymentInfo && paymentInfo.paymentStatus}</option>
<option value="Paid">Paid</option>
<option value="Pending">Pending</option>
</select>
</div>
<br />
<p className="ststxt">Order Status</p>
<div className="statSel">
<select name="OS" onChange={(e) => setOStatus(e.target.value)} id="format">
<option selected disabled>{orderStatus}</option>
<option value="Pending">Pending</option>
<option value="Baking">Baking</option>
<option value="Baked">Baked</option>
</select>
</div>
<br />
<p className="ststxt">Delivery Status</p>
<div className="statSel">
<select name="DS" onChange={(e) => setDStatus(e.target.value)} id="format">
<option selected disabled >{deliveryInfo && deliveryInfo.deliveryStatus}</option>
<option value="Pending">Pending</option>
<option value="Delivering">Delivering</option>
<option value="Delivered">Delivered</option>
</select>
</div>
<br />
<br />
<button className="sbmtbutton" style={{verticalAlign: 'middle'}} onClick={() => updateOrderHandler(order._id)}>
<span>Update Status </span>
</button>
</form>
in my actions.js
//admin update order stats
export const adminUpdateOrder = (id, orderData) => async (dispatch) => {
alert("Action recieved" + id + JSON.stringify(orderData))
try{
dispatch({type:A_UPDATE_ORDER_REQUEST})
const config = {
headers:{
'Content-Type': 'application/json'
}
}
const {data} = await axios.put(`/api/v1/admin/order/${id}`, orderData,config)
alert("link sended" + id + JSON.stringify(orderData))
dispatch({
type:A_UPDATE_ORDER_SUCCESS,
payload: data.success
})
}
catch(error){
dispatch({
type: A_UPDATE_ORDER_FAIL,
payload: error.response.data.message
})
}
}
I used alerts only for testing
I have two <select> inputs. I want to set the attribute as "disable" one of them at a specific value option from the other <select>.
The first one is:
<select ref="selectOption">
<option selected value="1" >Option 1</option>
<option value="2" >Option 2</option>
</select>
<select ref="selectTime" disabled={this.state.disabled}>
<option value="a" >January</option>
<option value="b" >Febreaury</option>
</select>
So, my idea is to set the state of the 2nd <select> as false when the option value = 2 from the first <select>
How can I do it? Or is there another way without react that I can do it? or with props? I'm pretty confused. I tried to do something like:
var option= ReactDom.findDOMNode(this.refs.selectOption).value;
if( option == '2' ) this.setState({disabled:true});
But it's not working. Tried to put it in componentDidUpdate but the component is not updating when I select a new value from the select, so that won't work. Ideas please.
EDIT:
I also have this solution with jquery but I want to use Reactjs.
$('#selectOption').change(function() {
$('#selectTime').prop('disabled', false);
if ($(this).val() == '2') {
$('#selectTime').prop('disabled', true);
}
})
I'm pretty confused on how to use ReactDom.findDOMNode(this.refs.selectOption) instead the jquery selectors
Here is a minimal example of how you could accomplish this, add an onChange event handler to your first select, setState in the event handler based on the value:
handleChange(event) {
let value = event.target.value;
this.setState({
disabled: value == '2'
});
}
render() {
return (
<div>
<select ref="selectOption" onChange={(e) => this.handleChange(e)}>
<option selected value="1" >Option 1</option>
<option value="2" >Option 2</option>
</select>
<select ref="selectTime" disabled={this.state.disabled}>
<option value="a" >January</option>
<option value="b" >Febreaury</option>
</select>
</div>
)
}
That would be the react way to achieve this:
export default class Test extends Component{
constructor(props) {
super(props)
this.state = {
selectOptionValue: '1'
}
}
handleOnChange = (e) => {
this.setState({
selectOptionValue: e.target.value
})
}
render(){
return (
<div>
<select defaultValue = "1" onChange={this.handleOnChange}>
<option value="1" >Option 1</option>
<option value="2" >Option 2</option>
</select>
<select disabled={ this.state.selectOptionValue === '2' }>
<option value="a" >January</option>
<option value="b" >Febreaury</option>
</select>
</div>
)
}
}
How about onChange event from this ? For your convenience:
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite La Croix flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
If you want to keep it simple and use pure javascript, you could just use the following snippet.
document.querySelector('select[ref="selectOption"]').addEventListener('change', function(e) {
document.querySelector('select[ref="selectTime"]').disabled = (e.target.value === '2') ? true : false;
})
<select ref="selectOption">
<option selected value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select ref="selectTime">
<option value="a">January</option>
<option value="b">Febreaury</option>
</select>
Here's another approach to define which state variable needs to be set.
state = { someStateVariable : "" }
render() {
return (
<select onChange={event => this._setSelected({ someStateVariable: event.target.value })}>
<option value="1">One</option>
...
</select>
);
}
_setSelected = newState => {
this.setState(newState)
}
Step 1 - Create state and set initial value an empty string
const [category,setCategory] = useState('');
Step 2 Map youre options and check id in the option value === select value then set selected to true
const renderedResults = results.map((result) => {
const selected = category === result.id ? "true" : '';
return (
<option selected={selected} key={result._id} value={result._id}>{result?.name}</option>
);
});
Step 3
<select
onChange={(e) => {
setCategory(e.target.value);
}}
className="form-select"
aria-label={"Default select example"}
>
<option value="">Select a category</option>
{renderedResults}
</select>
I'm using react and I want to get the value of the selected option of a dropdown in react but I don't know how. Any suggestions? thanks!
My dropdown is just a select like:
<select id = "dropdown">
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
The code in the render method represents the component at any given time.
If you do something like this, the user won't be able to make selections using the form control:
<select value="Radish">
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
So there are two solutions for working with forms controls:
Controlled Components Use component state to reflect the user's selections. This provides the most control, since any changes you make to state will be reflected in the component's rendering:
example:
var FruitSelector = React.createClass({
getInitialState:function(){
return {selectValue:'Radish'};
},
handleChange:function(e){
this.setState({selectValue:e.target.value});
},
render: function() {
var message='You selected '+this.state.selectValue;
return (
<div>
<select
value={this.state.selectValue}
onChange={this.handleChange}
>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{message}</p>
</div>
);
}
});
React.render(<FruitSelector name="World" />, document.body);
JSFiddle: http://jsfiddle.net/xe5ypghv/
Uncontrolled Components The other option is to not control the value and simply respond to onChange events. In this case you can use the defaultValue prop to set an initial value.
<div>
<select defaultValue={this.state.selectValue}
onChange={this.handleChange}
>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{message}</p>
</div>
http://jsfiddle.net/kb3gN/10396/
The docs for this are great: http://facebook.github.io/react/docs/forms.html
and also show how to work with multiple selections.
UPDATE
A variant of Option 1 (using a controlled component) is to use Redux and React-Redux to create a container component. This involves connect and a mapStateToProps function, which is easier than it sounds but probably overkill if you're just starting out.
Implement your Dropdown as
<select id = "dropdown" ref = {(input)=> this.menu = input}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Now, to obtain the selected option value of the dropdown menu just use:
let res = this.menu.value;
It should be like:
import React, { useState } from "react";
export default function App() {
const getInitialState = () => {
const value = "Orange";
return value;
};
const [value, setValue] = useState(getInitialState);
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<div>
<select value={value} onChange={handleChange}>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{`You selected ${value}`}</p>
</div>
);
}
you can see it here: https://codesandbox.io/s/quizzical-https-t1ovo?file=/src/App.js:0-572
Just use onChange event of the <select> object.
Selected value is in e.target.value then.
By the way, it's a bad practice to use id="...". It's better to use ref=">.."
http://facebook.github.io/react/docs/more-about-refs.html
As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to
use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple
you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown
whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList
1
remember you will always get the result as option value and not the dropdown text which is displayed on the screen
import React, { Component } from "react";
import { Server } from "net";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {
selectValue: ""
};
this.handleDropdownChange = this.handleDropdownChange.bind(this);
}
handleDropdownChange(e) {
this.setState({ selectValue: e.target.value });
}
render() {
return (
<div>
<div>
<div>
<select id="dropdown" onChange={this.handleDropdownChange}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div>Selected value is : {this.state.selectValue}</div>
</div>
</div>
);
}
}
export default InlineStyle;
Using React Functional Components:
const [option,setOption] = useState()
function handleChange(event){
setOption(event.target.value)
}
<select name='option' onChange={handleChange}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
class App extends React.Component {
state = {
selectedOption: null,
};
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
And you can check it out on this site.
It is as simple as that. You just need to use "value" attributes instead of "defaultValue" or you can keep both if a pre-selected feature is there.
....
const [currentValue, setCurrentValue] = useState(2);
<select id = "dropdown" value={currentValue} defaultValue={currentValue}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
.....
setTimeut(()=> {
setCurrentValue(4);
}, 4000);
In this case, after 4 secs the dropdown will be auto-selected with option 4.
I was making a drop-down menu for a language selector - but I needed the dropdown menu to display the current language upon page load. I would either be getting my initial language from a URL param example.com?user_language=fr, or detecting it from the user’s browser settings. Then when the user interacted with the dropdown, the selected language would be updated and the language selector dropdown would display the currently selected language.
In the spirit of the other answers using food examples, I got all sorts of fruit goodness for you.
First up, answering the initially asked question with a basic React functional component - two examples with and without props, then how to import the component elsewhere.
Next up, the same example - but juiced up with Typescript.
Then a bonus finale - A language selector dropdown component using Typescript.
Basic React (16.13.1) Functional Component Example. Two examples of FruitSelectDropdown , one without props & one with accepting props fruitDetector
import React, { useState } from 'react'
export const FruitSelectDropdown = () => {
const [currentFruit, setCurrentFruit] = useState('oranges')
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Or you can have FruitSelectDropdown accept props, maybe you have a function that outputs a string, you can pass it through using the fruitDetector prop
import React, { useState } from 'react'
export const FruitSelectDropdown = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
FruitSelectDropdown with Typescript
import React, { FC, useState } from 'react'
type FruitProps = {
fruitDetector: string;
}
export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit: string): void => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App: FC = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
Bonus Round: Translation Dropdown with selected current value:
import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
export const LanguageSelectDropdown: FC = () => {
const { i18n } = useTranslation()
const i18nLanguage = i18n.language
const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
const changeLanguage = (language: string): void => {
i18n.changeLanguage(language)
setCurrentI18nLanguage(language)
}
return (
<form>
<select
onChange={(event) => changeLanguage(event.target.value)}
value={currentI18nLanguage}
>
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
</form>
)
}
An invaluable resource for React/Typescript
You can handle it all within the same function as following
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>
<option value="5">5 dollars</option>
<option value="10">10 dollars</option>
</select>
as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!
If you want to get value from a mapped select input then you can refer to this example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fruit: "banana",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log("Fruit Selected!!");
this.setState({ fruit: e.target.value });
}
render() {
return (
<div id="App">
<div className="select-container">
<select value={this.state.fruit} onChange={this.handleChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</div>
</div>
);
}
}
export default App;
import {React, useState }from "react";
function DropDown() {
const [dropValue, setDropValue ]= useState();
return <>
<div>
<div class="dropdown">
<button class="btn btn-secondary" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
{dropValue==null || dropValue=='' ?'Select Id':dropValue}
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" onClick={()=> setDropValue('Action')} href="#">Action</a></li>
<li><a class="dropdown-item" onClick={()=> setDropValue('Another action')} href="#">Another action</a></li>
<li><a class="dropdown-item" onClick={()=> setDropValue('Something else here')} href="#">Something else here</a></li>
</ul>
</div>
</div>
</>
}
export default DropDown
<select value ={this.state.value} onChange={this.handleDropdownChange}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
As mentioned by Karen above you can just use the target value from the event triggered. Here is a small snippet of the code
`<select class="form-select py-2"
onChange={(e) => setVotersPerPage(e.target.value)}>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>`