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;
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}
/>
);
}
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>
);
}
import React, { PureComponent, Fragment } from 'react';
class Practice extends PureComponent {
state = {
options: [
{
name: 'Select…',
value: null,
},
{
name: 'Rui',
value: 3000,
},
{
name: 'Catla',
value: 3000,
},
{
name: 'Carpio',
value: 3000,
},
{
name: 'Tilapia',
value: 1750,
},
{
name: 'Mrigel',
value: 3000,
},
{
name: 'Pabda',
value: 3500,
},
{
name: 'Koi',
value: 750,
},
],
value: '?',
};
handleChange = (e) => {
this.setState({ value: e.target.value });
};
render() {
const { options, value } = this.state;
return (
<Fragment>
<select onChange={this.handleChange} value={value}>
{options.map(item => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
<p>Oxygen Demand: {value}</p>
</Fragment>
);
}
}
export default Practice;
Use useState to handle state of options and value
Use useCallback to handle change events on select field
Return your rendered JSX
import React, { useCallback, useState } from "react";
function Practice() {
const [options, setOptions] = useState([
{
name: "Select…",
value: null,
},
{
name: "Rui",
value: 3000,
},
{
name: "Catla",
value: 3000,
},
{
name: "Carpio",
value: 3000,
},
{
name: "Tilapia",
value: 1750,
},
{
name: "Mrigel",
value: 3000,
},
{
name: "Pabda",
value: 3500,
},
{
name: "Koi",
value: 750,
},
]);
const [value, setValue] = useState("?");
const handleChange = useCallback((e) => {
setValue(e.target.value);
}, []);
return (
<>
<select onChange={handleChange} value={value}>
{options.map((item) => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
<p>Oxygen Demand: {value}</p>
</>
);
}
export default Practice;
Convert like this:
import React, { useState, PureComponent, Fragment } from 'react';
let Practice = (praps) =>
let [options,soptions] = useState([
{
name: 'Select…',
value: null,
},
{
name: 'Rui',
value: 3000,
},
{
name: 'Catla',
value: 3000,
},
{
name: 'Carpio',
value: 3000,
},
{
name: 'Tilapia',
value: 1750,
},
{
name: 'Mrigel',
value: 3000,
},
{
name: 'Pabda',
value: 3500,
},
{
name: 'Koi',
value: 750,
},
]);
let [value,svalue]=useState('?')
let handleChange = (e) => {
svalue(e.target.value);
};
render() {
return (
<Fragment>
<select onChange={this.handleChange} value={value}>
{options.map(item => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
<p>Oxygen Demand: {value}</p>
</Fragment>
);
} }
export default Practice;
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
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