I tried using onChange to give me the value of the option I selected
and i get an error "TypeError: Cannot read property 'value' of undefined" what should i do?
import React, { useState,option } from 'react';
import Select from 'react-select'
export default function Change() {
const [category,setcat]=useState(20);
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
return(
<>
<Select onChange={(e)=>{setcat(e.target.value);}} value={options.value} options={options} />
<h1>result ={category}</h1>
</>
);
}
Here is the solution:
import React, { useState } from "react";
import Select from "react-select";
export default function Change() {
const [category, setCategory] = useState("Not select yet");
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
const handleChange = (selectedOption) => {
setCategory(selectedOption.value);
console.log(`Option selected:`, selectedOption);
};
return (
<>
<Select value={category} onChange={handleChange} options={options} />
<h1>result ={category}</h1>
</>
);
}
Visit to see live demo: CodeSandbox
Related
I just start learning Reactjs and I have trouble with Component. Here are my code:
export default function ChonLanguage() {
const [selectedOption, setSelectedOption] = useState([]);
const options = [
{ value: 'Vietnamese', label: 'Vietnamese' },
{ value: 'English', label: 'English' },
{ value: 'Chinese', label: 'Chinese' },
{ value: 'Japanese', label: 'Japanese' },
{ value: 'German', label: 'German' },
];
const handleChangeOption = () => {
return setSelectedOption;
}
return (
<Select className={`col-12 o-languages`}
onChange={handleChangeOption()}
options={options} />
)
}
It shown my options, but when I submit, I not save into Database. What should I change? Thanks
Made some minor changes to your code.
Kindly note:-
setSelectedOption is function of type React.dispatch<[]> which will update selectedOption state value so you need to pass some value in that.
useEffect is used to check the updated value of selectedOption, you may not use it.
export default function ChonLanguage() {
const [selectedOption, setSelectedOption] = useState([]);
const options = [
{ value: "Vietnamese", label: "Vietnamese" },
{ value: "English", label: "English" },
{ value: "Chinese", label: "Chinese" },
{ value: "Japanese", label: "Japanese" },
{ value: "German", label: "German" }
];
const handleChangeOption = (event) => {
return setSelectedOption(event.value);
};
useEffect(() => {
console.log(selectedOption);
}, [selectedOption]);
return (
<Select
className={`col-12 o-languages`}
onChange={(e) => {
handleChangeOption(e);
}}
options={options}
/>
);
}
I have some trouble with my react-select: When I click 'Submit', it save an object that have both 'value' and 'label' like this:
enter image description here
All I need is when I choose, it's show label list, and when I submit, it save only value. What can I do? Here are my code:
const [mainLang, setMainLang] = useState("");
const mainLangOptions = [
{ value: 'vi', label: 'Vietnamese' },
{ value: 'en', label: 'English' },
{ value: 'zh', label: 'Chinese' },
{ value: 'ja', label: 'Japanese' },
{ value: 'de', label: 'German' },
];
//This is Select part
<Select
onChange={(e) =>setMainLang(e)}
options={mainLangOptions}
/>
You need to set the option value as the mainLangOptions.value and the label as
mainLangOptions.label. By doing that you will display the label as option labels and save the value as the value of option tag. Check out the code below :
import React from "react";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
mainLanguage: ""
};
}
onOptionChangeHandler = (event) => {
this.state.mainLanguage = event.target.value;
console.log(this.state.mainLanguage);
};
render() {
const mainLangOptions = [
{ value: "vi", label: "Vietnamese" },
{ value: "en", label: "English" },
{ value: "zh", label: "Chinese" },
{ value: "ja", label: "Japanese" },
{ value: "de", label: "German" }
];
return (
<div>
<select onChange={this.onOptionChangeHandler}>
<option>Please choose one option</option>
{mainLangOptions.map((option, index) => {
return (
<option value={option.value} key={index}>
{option.label}
</option>
);
})}
</select>
</div>
);
}
}
export default App;
You must use e.target.value inside your setMainLang
<Select onChange={(e) => setMainLang(e.target.value)}>
This should work for your code but if it doesn't work, here is a complete code that I have tested in code sandbox and you can try it.
import React, { useState } from "react";
import { Select } from "#chakra-ui/react";
const Users = () => {
const [mainLang, setMainLang] = useState("");
const mainLangOptions = [
{ value: "vi", label: "Vietnamese" },
{ value: "en", label: "English" },
{ value: "zh", label: "Chinese" },
{ value: "ja", label: "Japanese" },
{ value: "de", label: "German" }
];
return (
<>
<Select onChange={(e) => setMainLang(e.target.value)}>
{mainLangOptions.map((op) => (
<option value={op.value}>{op.label}</option>
))}
</Select>
<h1>{mainLang}</h1>
</>
);
};
export default Users;
Here is my code:
https://codesandbox.io/s/inspiring-rhodes-jwv1zd?file=/src/App.js
To reproduce the issue:
Select Fruits from first select field.
Next, select one of the fruits from second field.
Next, again change the first field value from fruits to Vegetable, when I changed it to vegetables, the options on second field will be updated to vegetable lists, but still it keeps showing previous fruits as the selected one. How could I fix it? I want the first options from vegetables to be selected.
I have checked your code and made updates to the file.
First, there should be ref prop in the AppCreatableSelect.jsx Component.
This is updated AppCreatableSelect.jsx Component code.
import React, { forwardRef } from "react";
import { Controller } from "react-hook-form";
import ReactSelect from "react-select";
const AppCreatableSelect = forwardRef(
(
{
control,
options,
fieldName,
defaultValue,
errors,
className,
selectClassList,
isSearchable = true,
isClearable = true
},
ref
) => {
return (
<>
<Controller
name={fieldName}
className={`form-control ${className} ${
errors[fieldName] ? "is-invalid" : ""
}`}
control={control}
defaultValue={
options.length && options.find((row) => row.value === defaultValue)
}
selected={true}
render={({ field: { onChange, onBlur, name } }) => (
<ReactSelect
ref={ref}
isClearable={isClearable}
onBlur={onBlur} // notify when input is touched
inputRef={ref}
defaultValue={
options.length &&
options.find((row) => row.value.value === defaultValue)
}
onChange={onChange}
options={options}
className={selectClassList}
isSearchable={isSearchable}
/>
)}
/>
</>
);
}
);
export default AppCreatableSelect;
Here is the updated App.js Component code.
import "./styles.css";
import AppCreatableSelect from "./component/AppCreatableSelect";
import { useForm } from "react-hook-form";
import { useEffect, useState, useRef } from "react";
export default function App() {
const [types, setTypes] = useState([]);
const [items, setItems] = useState([]);
const [colors, setColors] = useState([]);
const itemsRef = useRef();
const colorsRef = useRef();
const {
control,
watch,
formState: { errors }
} = useForm();
const watchType = watch("types");
const watchItems = watch("items");
useEffect(() => {
setTimeout(() => {
setTypes([
{ label: "Fruits", value: "fruits" },
{ label: "Vegetables", value: "vegetables" }
]);
});
}, []);
useEffect(() => {
if (watchType) {
if (watchType.value === "fruits") {
setItems([
{ label: "Apple", value: "apple" },
{ label: "Orange", value: "orange" }
]);
itemsRef.current.setValue({ label: "Apple", value: "apple" });
}
if (watchType.value === "vegetables") {
setItems([
{ label: "Cabbage", value: "cabbage" },
{ label: "Cauliflower", value: "cauliflower" }
]);
itemsRef.current.setValue({ label: "Cabbage", value: "cabbage" });
}
}
}, [watchType]);
useEffect(() => {
if (watchItems) {
if (watchItems.value === "apple") {
setColors([
{ label: "Red Apple", value: "redApple" },
{ label: "Green Apple", value: "greenApple" }
]);
colorsRef.current.setValue({ label: "Red Apple", value: "redApple" });
}
if (watchItems.value === "orange") {
setColors([
{ label: "Red Orange", value: "redOrange" },
{ label: "Green Orange", value: "greenOrange" }
]);
colorsRef.current.setValue({ label: "Red Orange", value: "redOrange" });
}
if (watchItems.value === "cabbage") {
setColors([
{ label: "Red Cabbage", value: "redCabbage" },
{ label: "Green Cabbage", value: "greenCabbage" }
]);
colorsRef.current.setValue({
label: "Red Cabbage",
value: "redCabbage"
});
}
if (watchItems.value === "cauliflower") {
setColors([
{ label: "Red Cauliflower", value: "redCauliflower" },
{ label: "Green Cauliflower", value: "greenCauliflower" }
]);
colorsRef.current.setValue({
label: "Red Cauliflower",
value: "redCauliflower"
});
}
}
}, [watchItems]);
return (
<div className="App">
<AppCreatableSelect
control={control}
options={types}
fieldName="types"
errors={errors}
isClearable={false}
defaultValue={types[0]}
/>
<AppCreatableSelect
ref={itemsRef}
control={control}
options={items}
fieldName="items"
errors={errors}
isClearable={false}
defaultValue={items[0]}
/>
<AppCreatableSelect
ref={colorsRef}
control={control}
options={colors}
fieldName="itemColor"
errors={errors}
isClearable={false}
/>
</div>
);
}
I know it might be a similar question. But I cannot seem to find its solution. The code works perfectly fine. Whenever onChange function gets called. It is receiving selectionOption as props. But what are we passing in our this.handleChange? I tried passing e.target.value but it doesn't work. How is this code working? For example this is something im trying to implement to understand its logic. onChange = {(e)=>this.handleChange(e.target.value)}. But this doesnt work.
Example.js
import React from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";
import { stateOptions } from "./docs/data";
const options = [
{ value: "alabama", label: "Alabama" },
{ value: "florida", label: "Florida" },
{ value: "idaho", label: "Idaho" },
{ value: "washington", label: "Washington" },
{ value: "illinois", label: "Illinois" },
{ value: "vermont", label: "Vermont" }
];
export default class Example extends React.Component {
state = {
selectedOption: ""
};
handleChange = selectedOption => {
this.setState({ selectedOption });
// selectedOption can be null when the `x` (close) button is clicked
if (selectedOption) {
console.log(`Selected: ${selectedOption.label}`);
}
};
render() {
const { selectedOption } = this.state;
return (
<Select
multi={true}
name="colors"
value={selectedOption}
// what are we sending in this handleChange and how?
onChange={this.handleChange}
options={stateOptions}
/>
);
}
}
// what are we sending in this handleChange and how?
onChange={this.handleChange}
Your code is not in charge of that. It's up to react-select to pass a value in, and they do so on this line of code in their code base:
onChange(newValue, actionMeta);
So react-select passes in the new value as the first argument, and something called actionMeta as the second argument. All you need to do is tell react-select what function it should send that data to, which you do with the code onChange={this.handleSelect}
The string in the "value" field is passed.
Your handle function should expect a string:
handleChange = selectedOption(newValue:string) => {
//do something with this value here
};
in this case the value corresponds to the "value" here:
const options = [
{ value: "alabama", label: "Alabama" },
{ value: "florida", label: "Florida" },
{ value: "idaho", label: "Idaho" },
{ value: "washington", label: "Washington" },
{ value: "illinois", label: "Illinois" },
{ value: "vermont", label: "Vermont" }
];
I want to have a drop down in my application which allows the user to add an item to the dropdown. I am using React Sematic UI.
Sematic UI Dropdown ALlowAdditions
I am new to react hooks and I want to know how I can implement the onChange and onAddition function using hooks.
import React, { Component } from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 'English', text: 'English', value: 'English' },
{ key: 'French', text: 'French', value: 'French' },
{ key: 'Spanish', text: 'Spanish', value: 'Spanish' },
{ key: 'German', text: 'German', value: 'German' },
{ key: 'Chinese', text: 'Chinese', value: 'Chinese' },
]
class DropdownExampleAllowAdditions extends Component {
state = { options }
handleAddition = (e, { value }) => {
this.setState((prevState) => ({
options: [{ text: value, value }, ...prevState.options],
}))
}
handleChange = (e, { value }) => this.setState({ currentValue: value })
render() {
const { currentValue } = this.state
return (
<Dropdown
options={this.state.options}
placeholder='Choose Language'
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={this.handleAddition}
onChange={this.handleChange}
/>
)
}
}
export default DropdownExampleAllowAdditions
Any help would be greatly appreciated. Thanks in advance :)
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
const options = [
{ key: "English", text: "English", value: "English" },
{ key: "French", text: "French", value: "French" },
{ key: "Spanish", text: "Spanish", value: "Spanish" },
{ key: "German", text: "German", value: "German" },
{ key: "Chinese", text: "Chinese", value: "Chinese" }
];
const DropDownWithHooks = () => {
const [dropDownOptions, setDropDownOptions] = useState(options);
const [currentValue, setCurrentValue] = useState("");
const handleAddition = (e, { value }) => {
setDropDownOptions((prevOptions) => [
{ text: value, value },
...prevOptions
]);
};
const handleChange = (e, { value }) => setCurrentValue(value);
return (
<Dropdown
options={dropDownOptions}
placeholder="Choose Language"
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={handleAddition}
onChange={handleChange}
/>
);
};
export default DropDownWithHooks;
Working Sandbox