set default value for select in react js - reactjs

i am trying to set default value that is if this.state.items.gender is female in select option it must show female and if it is male the default value must me male
<select name="gender"
onChange={this.changeHandler}
defaultValue={this.state.items.gender} //onload this value must show in select input
required
style={styles.select}
>
<option style={styles.option} value="Male">
Male
</option>
<option style={styles.option} value="Female">
Female
</option>
</select>

default value is not working on simple html selection. You can do using the condition in the option in select like this.
<select
name="gender"
onChange={this.changeHandler}
//onload this value must show in select input
required
style={styles.select}
>
<option style={styles.option} value="Male" selected={this.state.items.gender === "Male"}>
Male
</option>
<option style={styles.option} value="Female" selected={this.state.items.gender === "Female"}>
Female
</option>
</select>;

This works perfectly fine to me.
import { useState } from 'react';
export default function App() {
const [gender, setGender] = useState('Female');
return (
<select
name="gender"
onChange={/* on change handler function */}
defaultValue={gender}
required
>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
);
}

Related

React repeating optgroup label on droplist

optgroup label is repeating on droplist
this is the dropdown
<Input
id="period"
name="period"
type="select"
required
onChange={handleChange}>
<option disabled selected>
Please Select
</option>
{periodLists.map((item) => (
<optgroup label={item.period_category}>
<option
key={item.id}
value={item.period_name}>
{item.period_name}
</option>
</optgroup>
))}
</Input>
this the data
I need display the droplist like this
You are creating a separate optgroup for each item.
You need to have two nested loops, an outer loop for the groups and an inner loop for the items.
<Input
id="period"
name="period"
type="select"
required
onChange={handleChange}>
<option disabled selected>
Please Select
</option>
{
[1, 2, 3].map((category) => (
<optgroup label={category}>
{
periodLists.map.map((item) => (
<option
key={item.id}
value={item.period_name}>
{item.period_name}
</option>
))
}
</optgroup>
))
}
</Input>

How to store selected values in useState

I am a beginner at React JS. I would like to learn how to store selected values in useState.
The form containts four different drop downs and I want to store this selected values in useState so that at the end of the multi step form, user can go back to edit the fields before sub.
import React, {useState} from 'react';
import './paperdetails.css';
import IncDecCounter from './IncDecCounter'
import {
Text
} from '#chakra-ui/react';
const PaperDetails = () => {
const [selected, setSelected] = useState();
return (
<div className='paper-details'>
<div className='paper-details_display_flex'>
<div className='left'>
<div className='left-calc_wrapper'>
<div>
<label>Type of Paper</label>
<select>
<option value="essay">Paraphrasing</option>
<option value="Custom Writing">Custom Writing</option>
<option selected value="Dissertation">Dissertation</option>
<option value="Research Paper">Research Paper</option>
<option value="essay">Essay</option>
<option value="Term Paper">Term Paper</option>
<option selected value="Admission Essay">Admission Essay</option>
<option value="Coursework">Coursework</option>
<option value="Book Review">Book Review</option>
<option selected value="Paraphrasing">Essay</option>
<option value="Physics Paper">Physics Paper</option>
</select>
</div>
<div>
<label>Study Level</label>
<select>
<option value="school">Bachelor</option>
<option value="college">College</option>
<option selected value="Bachelor">School</option>
<option value="Masters">Masters</option>
</select>
</div>
</div>
<div className='left_middle'>
<div className='calc-control'>
<label>Number of Pages</label>
<IncDecCounter />
</div>
<div className="select-deadline">
<label>Deadline</label>
<select className='deadline' value={selected} onChange={e=>setSelected(e.target.value)}>
<option value="1 hour">1 hour</option>
<option value="3 hours">3 hours</option>
<option selected value="8 hours">8 hours</option>
<option value="12 hours">12 hours</option>
<option value="24 hours">24 hours</option>
<option value="48 hours">48 hours</option>
<option selected value="3 days">3 days</option>
<option value="5 days">5 days</option>
<option value="7 days">7 days</option>
<option selected value="14 days">14 days</option>
</select>
<span color={'#785aec'} fontSize={'14px'}
fontWeight={'bold'}> Will be ready in: {selected}
</span>
</div>
</div>
<section className="writing-instructions">
<div className="writing_instructions">
<div className="d-flex">
<label className='instructions'>
Writing instructions
<span className='text-orange'> *required</span>
</label>
<input className="input-file" id="my-file" type="file"
accept="application/pdf,application/msword,
application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>
<label tabindex="0" for="my-file" className="input-file-trigger">
<span className='span--underlinel-blue'> Upload writing Instructions</span>
</label>
</div>
<div className='text-area'>
<textarea className='text-area_main'
placeholder='Type your instructions here. Please provide as many details as possible.'></textarea>
</div>
</div>
</section>
</div>
<div className='right'>
<div className='total-row'>
<div className='total-text'>
<h1 className='total-text_h1'>Total:</h1>
<span className='span_price'>$0.00</span>
</div>
</div>
</div>
</div>
</div>
)
}
export default PaperDetails;
How to store multiple values in state
to do this ,you will need to define state for all four select box like this
const [seleccedValue1,setSelectedValue1]=useState(null);
const [seleccedValue2,setSelectedValue2]=useState(null);
const [seleccedValue3,setSelectedValue3]=useState(null);
const [seleccedValue4,setSelectedValue4]=useState(null);
then you will need to handle on change event of each select box like this
<select onChange={(e)=>{setSelectedValue1(e.target.value)}}>
<option value="essay">Paraphrasing</option>
<option value="Custom Writing">Custom Writing</option>
<option selected value="Dissertation">Dissertation</option>
<option value="Research Paper">Research Paper</option>
<option value="essay">Essay</option>
<option value="Term Paper">Term Paper</option>
<option selected value="Admission Essay">Admission Essay</option>
<option value="Coursework">Coursework</option>
<option value="Book Review">Book Review</option>
<option selected value="Paraphrasing">Essay</option>
<option value="Physics Paper">Physics Paper</option>
</select>
you can do the same for other select boxes as well
Please checkout this question:
It was already answered here:
React JSX: selecting "selected" on selected <select> option
Here is how you store value of any input field in useState();
const [selected,setSelected] = useState({});
function handleChange(event){
setSelected({...selected,[event.targe.id]=event.target.value});
}
return(
<select
id={"id_0"}
value={selected["id_0"]}
onChange={(event)=>(handleChange(event))}>
......."your code continue here"
and here is how you handle multiple input fields.
<select id={'id_1'} value={selected['id_1']}
onChange={(event)=>(handleChange(event))}/>
<select id={'id_2'} value={selected['id_2']}
onChange={(event)=>(handleChange(event))}/>

Simple React form is not showing the default value (reactHooks)

I'm following the official React docs to build a simple form which, however, doesn't work as intended.
const [value, setValue] = useState("banana")
...
<form onSubmit={handleSubmit}>
<label>
Pick your favorite flavor:
<select value={value} onChange={handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
As far as I understood, it has to display "banana" as the initial value, whereas it shows "grapefruit". Why is it so?
Here's the link to the docs: https://reactjs.org/docs/forms.html
In the "Forms" section there's an example from where I took the code. It, however, uses class-based components while I use reactHooks. Might it be the problem?
Many thanks!
It shows the first option because value isn't an attribute of <select>. If you want to select one, you need to add a selected attribute to one of the options.
For example:
<label>
Pick your favorite flavor:
<select onChange={handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option selected={true} value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
This is generally written as
const options = ["grapefruit", "lime", "coconut", "mango"];
const selectedValue = "lime";
<label>
Pick your favorite flavor:
<select onChange={handleChange}>
{options.map(o => (<option value={o} selected={o == selectedValue}>{o}</option>)}
</select>
</label>
<input type="submit" value="Submit" />
It is because banana is not in options. If option's value is not present then it will by default pick the first one(Default behaviour). DEMO
import "./styles.css";
import { useState } from "react";
export default function App() {
const [value, setValue] = useState("mango");
const handleChange = (e) => {
setValue(() => {
return e.target.value;
});
};
return (
<div className="App">
<select value={value} onChange={handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</div>
);
}

How to use defaultValue in the select tag in a functional component?

I have a functional component that contains a select tag with a few options.
I want to set cars as the default value.
Initially, I simply added selected in the car's option but react gave me a warning saying I should be using defaultValue in the select tag instead. I was wondering how I can do that?
Thanks in advance.
function ChooseOptions(props) {
return (
<div>
<h2>Choose Options</h2>
<label>
New Only <input type="checkbox" />
</label>
<label
htmlFor="selectType"
style={{ display: "block" }}
defaultValue="Cars"
>
Select Type
<select id="selectType">
<option value="all">All</option>
<option value="cars">Cars</option>
<option value="trucks">Trucks</option>
<option value="convertibles">Convertibles</option>
</select>
</label>
</div>
);
}
Try this.
You will get the change value in 'onChange' props,
You can set value by passing 'value' props
<select id="selectType" defaultValue="cars">
<option value="all">All</option>
<option value="cars">Cars</option>
<option value="trucks">Trucks</option>
<option value="convertibles">Convertibles</option>
</select>

Angularjs select validation not working

I want to tell user to select any option from select other than first (index=0). I saw few examples and tried but not working for me:
<select ng-model="patient.gender" name="gender" class="form-control" required>
<option>- Select -</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<div class="error" ng-show="Form.gender.$invalid">
Select gender
</div>
What to change here?
provide empty(default value) to option, so required field validation will fire on selection.
Html:
<select ng-model="patient.gender" name="gender" class="form-control" required>
<option value=''>- Select -</option> //Default value to empty
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>

Resources