Can't save value into database through Reactjs Component - reactjs

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}
/>
);
}

Related

I want to save just value in react-select

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;

how to show only the result of the selection?

my current code shows a complete list of clinics, when in the selector I choose a province, it shows me the clinics located in that province, what I would like is not to show the complete list of clinics at the beginning but only show the result when filtering by province. That is to say, when starting the application that only the selection is seen and once the province is selected, the results will be shown.
import React, { useState, useEffect } from 'react'
import Select, { SingleValue } from 'react-select'
import { getClinic } from '../../api/drupalAPI'
import {Clinic} from '#icofcv/common';
export const SearchFilterClinics = () => {
////filter
type OptionType = {
value: string;
label: string;
};
const provincesList: OptionType[] = [
{ value: 'Todos', label: 'Todos' },
{ value: 'Alava/Araba', label: 'Alava/Araba' },
{ value: 'Albacete', label: 'Albacete' },
{ value: 'Alicante', label: 'Alicante' },
{ value: 'Almería', label: 'Almería' },
{ value: 'Avila', label: 'Avila' },
{ value: ' Badajoz', label: ' Badajoz' },
{ value: 'Islas Baleares', label: 'Islas Baleares' },
{ value: 'Barcelona', label: 'Barcelona' },
{ value: 'Burgos', label: 'Burgos' },
{ value: 'Cáceres', label: 'Cáceres' },
{ value: 'Cádiz', label: 'Cádiz' },
{ value: 'Castellón', label: 'Castellón' },
{ value: 'Ciudad Real', label: 'Ciudad Real' },
{ value: 'Córdoba', label: 'Córdoba' },
{ value: 'A Coruña/La Coruña', label: 'A Coruña/La Coruña' },
{ value: 'Cuenca', label: 'Cuenca' },
{ value: 'Gerona/Girona', label: 'Gerona/Girona' },
{ value: 'Granada', label: 'Granada' },
{ value: 'Guadalajara', label: 'Guadalajara' },
{ value: 'Gipuzkoa/Guipuzcoa', label: 'Gipuzkoa/Guipuzcoa' },
{ value: 'Huelva', label: 'Huelva' },
{ value: 'Huesca', label: 'Huesca' },
{ value: 'Jaen', label: 'Jaen' },
{ value: 'León', label: 'León' },
{ value: 'Lérida/Lleida', label: 'Lérida/Lleida' },
{ value: 'La Rioja', label: 'La Rioja' },
{ value: 'Lugo', label: 'Lugo' },
{ value: 'Madrid', label: 'Madrid' },
{ value: ' Málaga', label: ' Málaga' },
{ value: 'Murcia', label: 'Murcia' },
{ value: 'Navarra', label: 'Navarra' },
{ value: 'Orense/Ourense', label: 'Orense/Ourense' },
{ value: 'Asturias', label: 'Asturias' },
{ value: 'Palencia', label: 'Palencia' },
{ value: 'Las Palmas', label: 'Las Palmas' },
{ value: 'Pontevedra', label: 'Pontevedra' },
{ value: 'Salamanca', label: 'Salamanca' },
{ value: 'S.C.Tenerife', label: 'S.C.Tenerife' },
{ value: 'Cantabria', label: 'Cantabria' },
{ value: 'Segovia', label: 'Segovia' },
{ value: ' Sevilla', label: ' Sevilla' },
{ value: 'Soria', label: 'Soria' },
{ value: 'Tarragona', label: 'Tarragona' },
{ value: 'Teruel', label: 'Teruel' },
{ value: 'Toledo', label: 'Toledo' },
{ value: 'Valencia', label: 'Valencia' },
{ value: 'Valladolid', label: 'Valladolid' },
{ value: 'Bizkaia/Vizcaya', label: 'Bizkaia/Vizcaya' },
{ value: 'Zamora', label: 'Zamora' },
{ value: 'Zaragoza', label: 'Zaragoza' },
{ value: 'Ceuta', label: 'Ceuta' },
{ value: 'Melilla', label: 'Melilla' },
]
const [clinicList, setClinicList] = useState<Clinic[]>([]);
const [clinicListFilteredSelect, setClinicListFilteredSelect] = useState<Clinic[]>([]);
const [filterSelectClinic, setFilterSelectClinic] = useState<SingleValue<OptionType>>(provincesList[0]);
const fetchClinicList = async () => {
getClinic().then((response)=>{
console.log(response)
setClinicList(response);
setClinicListFilteredSelect(response)
}).catch ( (error) => {
console.error(error);
throw error;
});
}
const handleChangeSelect = (provinceList: SingleValue<OptionType>) =>{
console.log(provinceList)
setFilterSelectClinic(provinceList);
filterSelect(provinceList );
}
const filterSelect=(termSearch)=>{
const resultFilterSelect = clinicList.filter((element) => {
if(element.province?.toString().toLowerCase().includes(termSearch.value.toLowerCase() )
){
return element;
}
});
setClinicListFilteredSelect(resultFilterSelect);
}
useEffect (() => {
fetchClinicList();
}, []);
return (
<>
<div>
<h1>Encuentra tu clínica</h1>
</div>
<div>
<Select
defaultValue={filterSelectClinic}
options={provincesList}
onChange={handleChangeSelect}
/>
{
clinicListFilteredSelect.map((clinic) => (
<div>
<div>{clinic.title}</div>
<div>{clinic.propsPhone}</div>
<div>{clinic.mobile}</div>
<div>{clinic.email}</div>
<div>{clinic.province} </div>
<div>{clinic.registry}</div>
</div>
))
}
</div>
</>
)
}
You're setting clinicListFilteredSelect in your useEffect with an empty dependancy array. This means when your component mounts it will set clinicListFilteredSelect to the response of your API call.
If you instead want to only show the response when filterting by clinics, you need to move this call to the event handler and remove the useEffect.
Something like:
const handleChangeSelect = async (provinceList: SingleValue<OptionType>) => {
getClinic().then((response) => {
setClinicList(response);
setClinicListFilteredSelect(response)
setFilterSelectClinic(provinceList);
filterSelect(provinceList );
}).catch ((error) => {
console.error(error);
throw error;
});
}

Adding selected options to state array reactjs

I am working on an ecommerce application
I am using react-select to select multi category
I want to get the value selected by the use and add it to the state category
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const AddProductModal = ({addOpenProductModal, setAddOpenProductModal}) => {
const [category, setCategory] = useState({
category: []
})
const handleChange = (e) => {
// let {label, value} = e.target;
console.log(e);
// setCategory({ category: [...category, 'new value'] })
}
return (
<div>
<Select
onChange={handleChange}
isMulti
name="categories"
options={options} />
</div>
)
}
export default AddProductModal

How to implement AddAdiditions in React Sematic UI using Hooks?

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

Updating React-Select menu with setState?

I am trying to get React-Select to display a different dropdown menu list based on the user input:
const helpOptions = [
{ value: "user", label: "u:<String> User Operator" },
{ value: "day", label: "d:<Number> Date Operator" },
{ value: "week", label: "w:<Number> Week Operator" },
{ value: "month", label: "m:<Number> Month Operator" },
{ value: "bracket", label: "() Brackets Operator" },
{ value: "and", label: "&& AND Operator" },
{ value: "or", label: "|| OR Operator" },
{ value: "not", label: "~ NOT Operator" }
];
const userOptions = [
{ value: "john", label: "u:John" },
];
class Field extends Component {
state = {
menu: userOptions,
value: ""
};
onInputChange = e => {
if (e.substring(0, 1) === "?") {
this.setState(
{
menu: helpOptions,
value: e
},
() => {
console.log(this.state.menu);
}
);
} else {
this.setState({
menu: []
});
}
};
render() {
const { menu, value } = this.state;
console.log("rendering");
console.log(menu);
return (
<Select
isMulti
value={value}
options={menu}
onInputChange={this.onInputChange}
/>
);
}
}
The desired behavior is if the first character of the text entered into the search field is a '?' the menu will populate with the const of helpOptions. Otherwise it would be (for now) empty.
Codesandbox: https://codesandbox.io/s/runtime-sun-cfg71
From the console logs, I seem to be getting the values and the rendering seems to be working. However, I am still getting 'No Option' as a response from the React-Select component.
How can I dynamically change the React-Select menu items based on the user's input?
Update
If you want your state to update after calling setState you need use a function that will work only after updating the state:
this.setState(state => ({
...state,
menu: helpOptions
}));
First of all you need to call a constructor in your component. Secondly, in documentation to react-select prop value doesn't exist. Thirdly, it’s good practice to copy your state before changing.
Here is a valid code:
import React, { Component } from "react";
import Select from "react-select";
import "./styles.css";
const helpOptions = [
{ value: "user", label: "u:<String> User Operator" },
{ value: "day", label: "d:<Number> Date Operator" },
{ value: "week", label: "w:<Number> Week Operator" },
{ value: "month", label: "m:<Number> Month Operator" },
{ value: "bracket", label: "() Brackets Operator" },
{ value: "and", label: "&& AND Operator" },
{ value: "or", label: "|| OR Operator" },
{ value: "not", label: "~ NOT Operator" }
];
const userOptions = [
{ value: "john", label: "u:John" },
{ value: "stan", label: "d:Stan" },
{ value: "addison", label: "w:Addison" },
{ value: "dionis", label: "m:Dionis" }
];
class Field extends Component {
constructor(props) {
super(props);
this.state = {
menu: userOptions,
value: ""
};
}
onInputChange = e => {
if (e.substring(0, 1) === "?") {
console.log("help");
this.setState({
...this.state,
menu: helpOptions
});
} else {
this.setState({
...this.state,
menu: userOptions
});
}
};
render() {
const { menu, value } = this.state;
return <Select isMulti options={menu} onInputChange={this.onInputChange} />;
}
}
export default Field;
Here is an example on codesandbox.

Resources