getting input with select - reactjs

in my react application I wish to change the input to a select tag in my form , how can I do that?
<form className="form-maker" onSubmit={this.handleSubmit}>
Type:
<input name="inputType" type="text" onChange={this.handleChange} />
</form>
in to this:
<select>
<option value="text">text</option>
<option value="color">color</option>
<option value="date">date</option>
<option value="email">email</option>
<option value="tel">tel</option>
<option value="number">number</option>
</select>

The handleChange goes in the <select /> element, similar to the <input />.
Here is a small running example:
class App extends React.Component {
state = { value: "text" };
onSelect = ({target}) => this.setState({value: target.value})
render() {
const { value } = this.state;
return (
<div>
<select onChange={this.onSelect}>
<option value="text">text</option>
<option value="color">color</option>
<option value="date">date</option>
<option value="email">email</option>
<option value="tel">tel</option>
<option value="number">number</option>
</select>
<div>{`Selectet Value is ${value}`}</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>
You will probably want an array of these values, so it will be easier to render the <options /> and set the selected attribute.
Here is another example, this time with a different default value selected:
const values = [
"text", "color", "date", "email", "tel","number"
]
class App extends React.Component {
state = { value: "date" };
onSelect = ({target}) => this.setState({value: target.value})
render() {
const { value } = this.state;
return (
<div>
<select onChange={this.onSelect}>
{values.map(val => <option key={val} value={val} selected={val === value}>{val}</option>)}
</select>
<div>{`Selectet Value is ${value}`}</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />

Related

How to get the value of custom atttributes in react hooks?

How do I get the value of custom attributes using react hooks?
Here is sample code in code sandbox : demo live
code
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [value, setValue] = useState("");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<select
onChange={(e) => {
console.log("value", e.target.value);
console.log("description", e.target.description);
setValue(e.target.value);
}}
name="cars"
id="cars"
>
<option value="volvo" description="hahahahaa">
Volvo
</option>
<option value="saab" description="hehehehehe">
Saab
</option>
<option value="opel" description="hoooooooo">
Opel
</option>
<option value="audi" description="huuuuuuuuuu">
Audi
</option>
</select>
</div>
);
}
I am able to get the value of attribute value but not the custom description.
I get undefined console.log("description", e.target.description);
What is wrong here?
e.target give you the select tag, you can get the option tag and the description like this:
console.log("description", e.target.childNodes[e.target.selectedIndex].getAttribute("description"));
In your example target is the <select> and you would need to traverse to the selected option and get the attribute value.
It really doesn't seem practical to store data in a custom option attribute when you could use a hashmap with values as keys
const Example = () => {
const [desc, setDesc] = React.useState('')
const descriptions = {
volvo:'hahahahaa',
saab:'hehehehehe',
opel:'hoooooooo'
}
const handleChange = (e)=>{
const val = e.target.value,
des = descriptions[val]
console.clear()
console.log("value",val);
console.log("description", des);
setDesc(des)
}
return (
<div>
<div>Description: {desc}</div>
<select
onChange={handleChange}
name="cars"
id="cars"
>
<option value="volvo">
Volvo
</option>
<option value="saab">
Saab
</option>
<option value="opel" >
Opel
</option>
</select>
</div>
);
};
// Render it
ReactDOM.render(
<Example title="Example using Hooks:" />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Multiple Dropdown in reactjs

I want to select multiple dropdown values in react js using Dynamic Values.
<Col lg="10">
<select id="facility_id" className="form-control select2" value={this.state.facility_id} onChange={this.handleChange} title="Type Growing system" isMulti>
<option value="0">None</option>
{this.state.facilities.map((faci, key) =>
<option key={key} value={faci.facility_id}>{faci.facility_name}</option>
)}
</select>
react-select is not working for me . Any other options available?
Use element attr multiple instead of isMulti.
Try something like this.
const Select = () => {
const [selections, setSelections] = React.useState(['b', 'c']);
const onSeletionChange = val => {
let sels = [...selections];
if (sels.includes(val)) {
sels = sels.filter(x => x !== val);
} else {
sels.push(val);
}
setSelections(sels);
}
return (
<div>
Multi Select (select again to remove)
<select
id="facility_id"
className="form-control select2"
value={selections}
onChange={(e) => {
console.log(e.target.value);
onSeletionChange(e.target.value);
}}
title="Type Growing system"
multiple
>
<option value="0" key="0">None</option>
{["a", "b", "c"].map((faci, key) => (
<option key={key} value={faci}>
{faci}
</option>
))}
</select>
</div>
);
};
const domContainer = document.querySelector('#app');
ReactDOM.render(<Select />, domContainer);
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<div id="app"> </div>

componentDidUpdate function doesn't get called

I've created a React component to render another component inside.when I change the select element in the parent component the componentDidUpdate function doesn't get called in the child component
component1:
let ExtraParam = [];
const handleChange = (e) => {
ExtraParam[e.target.name] = e.target.value;
}
const Flights = () => {
return (
<div>
<div className="row">
<div className='col-6 col-md-3 mt-5'>
<select onChange={handleChange} name="age" className="browser-default custom-select">
<option>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
</div>
<Datatable Api='/api/Flights' Columns={columns} extraParam {ExtraParam} />
</div>
)
}
component2:
componentDidUpdate(prevProps) {
if (this.props.extraParam !== prevProps.extraParam)
{
console.log('changed');
}
}

connecting a select tag to a form, and then reseting it at submit

hi guys I'm trying to reset a select tag after the submit using React,I connected the first option to the state which is :
state = {
inputs: [],
tempInput: {
inputType: 'Please select a type'
}
};
so I basically select a type in my form, it updates the tempInput object with the inputType, and then add it to the array of objects,
<div className="formG">
<form className="form-maker" onSubmit={this.handleSubmit}>
<select onChange={this.onSelect}>
<option>{this.state.tempInput.inputType}</option>
<option value="text">text</option>
<option value="color">color</option>
<option value="date">date</option>
<option value="email">email</option>
<option value="tel">tel</option>
<option value="number">number</option>
</select>
<button>Submit</button>
</form>
this is my on select method:
onSelect = ({ target }) => {
const { tempInput } = this.state;
tempInput.inputType = target.value;
this.setState({ tempInput });
};
handleSubmit = e => {
e.preventDefault();
how to do that in handleSubmit? to put the tempInput.inputType to ="Please pick a type"
};
This is an uncontrolled element.
If you want to control the value of an input / select you need to set it via your state:
const values = [
"text", "color", "date", "email", "tel","number"
]
class App extends React.Component {
state = { value: "" };
onSelect = ({target}) => this.setState({value: target.value})
handleSubmit = () => {
console.log('submit with ',this.state.value)
this.setState({value: ''})
}
render() {
const { value } = this.state;
return (
<div>
<select onChange={this.onSelect}>
<option>Select A value</option>
{values.map(val => <option key={val} value={val} selected={val === value}>{val}</option>)}
</select>
<button onClick={this.handleSubmit}>Submit</button>
<div>{`Selectet Value is ${value}`}</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
Here is the example without the array:
class App extends React.Component {
state = { value: "" };
onSelect = ({ target }) => this.setState({ value: target.value })
handleSubmit = () => {
console.log('submit with ', this.state.value)
this.setState({ value: '' })
}
render() {
const { value } = this.state;
return (
<div>
<select onChange={this.onSelect}>
<option selected={value === ""} value="">Select A value</option>
<option selected={value === "text"} value="text">text</option>
<option selected={value === "color"} value="color">color</option>
<option selected={value === "date"} value="date">date</option>
<option selected={value === "email"} value="email">email</option>
<option selected={value === "tel"} value="tel">tel</option>
<option selected={value === "number"} value="number">number</option>
</select>
<button onClick={this.handleSubmit}>Submit</button>
<div>{`Selectet Value is ${value}`}</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>
Of course there is a lot of repeated code here, in programming there is the "DRY" principle (Do Not Repeat Yourself).
This is why we use loops like Array.prototype.map
in your onSelect function, you're mutate the state object(tempInput.inputType = target.value;), it is not a good practice in react.
if you want your select value controlled by the react state, first you need to bind it's value with react state, which it's called a controlled component, like:
<select onChange={this.onSelect} value={this.state.tempInput.inputType}>

set state based off option value in a select

How can I use the options in the select in my state?
this.state = {
posts: [],
question: '',
body: '',
postType: '',
}
<select value="types" className="u-full-width">
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
I am not sure how to set the state of postType based off what the user selects.
getPostType() {
const type =
this.setState({ postType: type });
}
You need to add a function to handle the changes on the select, save the value in the state and pass it to the select.
Something like this:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
postType: 'Option 1',
}
this.onChange = this.onChange.bind(this)
};
onChange(event){
this.setState({
postType: event.target.value
})
}
render() {
return (
<div>
<select value={this.state.postType} onChange={this.onChange} className="u-full-width">
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
{this.state.postType}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
This is called a controlled component. You can read more about it here.
I think that what you're looking for is the following:
<select className="u-full-width"
onChange= this.handleOnChange.bind(this)
ref={value => this.refName = value}>
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
handleOnchange(e){
e.preventDefault(e);
const type = this.refName.value;
setState({postType: type});
}
Hope it was helpful!
You can try the following implementation.
class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
question: '',
body: '',
postType: 'Question',
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({postType: event.target.value});
}
render() {
return (
<form>
<label>
Select your postType:
<select className="u-full-width" value={this.state.postType}
onChange={this.handleChange}>
<option value="Question">Question</option>
<option value="Discussion">Discussion</option>
<option value="Clout">Clout</option>
</select>
</label>
</form>
);
}
}
ReactDOM.render(
<Sample />,
document.getElementById('root')
);

Resources