How is handleChange receiving props? React - reactjs

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" }
];

Related

Can't save value into database through Reactjs Component

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 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 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

How to Get Selected Value from a Select Input in react

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

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