Reactjs - Select box with varying first option based on passed attribute - reactjs

I am trying to show the first option different based on an attribute I pass.
In the search page, I want the user to be able to select "Any" option.
In the edit profile page, "Any" option should not be shown because that is only for search.
Edit profile page
<option value="0" disabled selected>
Select Religion
</option>
Search page
<option value="Any" selected>
Any Religion
</option>
Search profile page has this code:
import React, { Component } from 'react'
..
import ReligionInput from '../edit-profile/religion-input'
..
..
<ReligionInput value={religion} change={this.changeReligion} any="Y" />
...
And ReligionInput has a check for any == Y or not but its not working and always has the Any option. What is wrong with the code below ?
import religionOptions from './religion-options'
const InputReligion = ({ value, change, any }) => (
<div className="edit_religion_div">
<Select
placeholder="Select option"
value={value}
valueChange={e => change('religion', e)}
className="edit_religion my2"
>
{any} == 'Y' ?
`<option value="Any" selected>
Any Religion
</option>` :
`<option value="0" disabled selected>
Select Religion
</option>`
{religionOptions.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>;
})}
</Select>
</div>
)
InputReligion.propTypes = {
value: PropTypes.string.isRequired,
change: PropTypes.func.isRequired,
}
All other options come from religionOptions.

A dirty way of doing it would be.
<option value={ any=='Y' ? '0' : 'Any' } selected>{ any=='Y' ? 'select' : 'any religion' }</option>
Yeah, not really a fan of those conditions either.
A cleaner and more readable approach would be:
const InputReligion = (props) => {
let defaultOption = null;
if (props.any == 'Y' ) {
defaultOption = <option value='Any' selected>Any religion</option>
} else {
defaultOption = <option value='0' selected disabled>Select Religion</option>
}
return (
<div className="edit_religion_div">
<select placeholder="Select Option"
className="edit_religion my2"
value={ props.value }
valueChange={ e => change('religion', e)}
>
{ defaultOption }
{
religion.map( (e, key) => {
return <option key={ key } value={ e.value }>{ e.name }</option>
})
}
</select>
</div>
)
}

Related

How to have second dropdown menu values be dependent on value of first dropdown menu in React render function

In the render function of a React component, I have the following code
<select name="env" id="env">
<option value="Dev">Dev</option>
<option value="Staging">Staging</option>
<option value="Prod">Prod</option>
</select>
<select name="region" id="region">
<option value="option1">op1</option>
<option value="option2">op2</option>
<option value="option3">op3</option>
<option value="option4">op4</option>
</select>
If Dev option is selected in first dropdown, there should only be op1 choice available in the 2nd dropdown. Similarly if Staging is selected, then op1, op2 and op3 are the available choices. If Prod is selected, then all 4 choices are available. How can I achieve this in React?
You should render different region options by env.
const regionsByEnv = {
Dev: ["option1"],
Staging: ["option1", "option2", "option3"],
Prod: ["option1, option2, option3, option4"],
};
const YourComponent = () => {
const [env, setEnv] = useState("");
const regionOptions = useMemo(() => {
if (!env) {
return regionsByEnv.Prod.map((option) => (
<option value={option} key={option}>
{option}
</option>
));
}
return regionsByEnv[env].map((option) => (
<option value={option} key={option}>
{option}
</option>
));
}, [env]);
return (
<>
<select
value={env}
onChange={(e) => setEnv(e.target.value)}
name="env"
id="env"
>
<option value="Dev">Dev</option>
<option value="Staging">Staging</option>
<option value="Prod">Prod</option>
</select>
<select name="region" id="region">
{regionOptions}
</select>
</>
);
};
You should filter option for select region base on selected option of select env. So you can create a state for handling value of select env
export default function App() {
const [select1, setSelect1] = useState("Dev");
const filterOption2 = allOption2.filter((i) => {
return (
(select1 === "Dev" && i.value === "option1") ||
(select1 === "Staging" && i.value !== "option4") ||
select1 === "Prod"
);
});
return (
<div className="App">
<select name="env" id="env" onChange={(e) => setSelect1(e.target.value)}>
<option value="Dev">Dev</option>
<option value="Staging">Staging</option>
<option value="Prod">Prod</option>
</select>
<select name="region" id="region">
{filterOption2.map((op) => (
<option key={select1 + op.value} value={op.value}>
{op.name}
</option>
))}
</select>
</div>
);
}
const allOption2 = [
{
name: "op1",
value: "option1"
},
{
name: "op2",
value: "option2"
},
{
name: "op3",
value: "option3"
},
{
name: "op4",
value: "option4"
}
];
You can check in my codesandbox

Multiple Dropdown using ReactJS

I am designing and developing a CRUD API where it has 3 dropdowns. If I click on 1 dropdown and select an option it should prompt to another dropdown.
The error I am getting, which is at handlechange(), is:
"`TypeError: Cannot set property 'param_type' of undefined`".
Where is the mistake i am doing?
Below is the code:
handleChange(event) {
console.log(event.target.id)
var errors = this.state.errors
if (event.target.id.split('_')[0] == 'name') {
var ids = event.target.id.split('_')
let szs = this.state.parameters
szs[ids[1]].param_name = event.target.value
this.setState({ parameters: szs })
}
else if (event.target.id.split('_')[0] == 'type') {
var ids = event.target.id.split('_')
let szs = this.state.parameters
szs[ids[1]].param_type = event.target.value
this.setState({ parameters: szs })
console.log(szs)
}
else if (event.target.id.split('_')[0] == 'data') {
var ids = event.target.id.split('_')
let szs = this.state.parameters
szs[ids[1]].param_data = event.target.value
this.setState({ parameters: szs })
}
else if (event.target.id.split('_')[0] == 'type_of_configuration_data') {
var ids = event.target.id.split('_')
let szs = this.state.parameters
szs[ids[1]].type_of_config_data = event.target.value
this.setState({ parameters: szs })
}
this.setState({
errors: errors
})
}
The render which I do is:
{this.state.parameters[idx_fields].param_type === "list"?
<Col md="2">
<Label>Data <span style={{ color: "red" }}>*</span></Label>
<select id={"data" + '_' + idx_fields} className="form-control select2" value=
{this.state.parameters[idx_fields].param_data} onChange={this.handleChange} title="Kind">
<option value="type_of_configuration_data">Type of Configuration</option>
<option value="user-defined-data">User Defined Data</option>
</select>
</Col>
:null}
{this.state.parameters[idx_fields].param_data === "type_of_configuration_data"?
<Col md="2">
<Label>Type of configurations <span style={{ color: "red" }}>*</span></Label>
<select id={"type_of_configuration_data" + '_' + idx_fields} className="form-control select2" value=
{this.state.parameters[idx_fields].type_of_config_data} onChange={this.handleChange} title="Kind">
<option value="crops">Crops</option>
<option value="tanks">Tanks </option>
<option value="type-of-growing-system">Type Of Growing System </option>
<option value="seeding-units">Seeding Units </option>
<option value="batch-units">Batch Units </option>
<option value="facilities">Facilities </option>
<option value="users">Users </option>
<option value="task-categories">Task categories </option>
</select>
</Col>
:null}
What the error says is the object from where you are using the property is not present in other words its undefined.
In the code param_type is used here, szs[ids[1]].param_type. Console and check if the required property is present in szs[ids[1]].
You can use if statement here:
if (szs[ids[1]]) {
szs[ids[1]].param_type = event.target.value;
}
or szs[ids[1]]?.param_type = event.target.value;

how to make option selected by default in react

I am using this.state.something in option tag to make it selected default.
but it is showing me error at this.state.editusertype
<select name="usertype" className="form-control" value={this.state.editusertype}>
<option value="">Select</option>
<option value="Employee" {this.state.editusertype == "Employee" ? "selected" : ""} >Employee</option>
<option value="Manager" {this.state.editusertype == "Manager" ? "selected" : ""}>Manager</option>
</select>
If you want to have a default option, set a default value for your select tag. It should correspond with a matching option. See sandbox: https://codesandbox.io/s/young-pine-zmpvr
class App extends React.Component {
state = {
editusertype: "Manager"
};
handleOnChange = event => {
this.setState({
editusertype: event.target.value
});
};
render() {
return (
<div>
<select
name="usertype"
className="form-control"
onChange={this.handleOnChange}
value={this.state.editusertype}
>
<option value="">Select</option>
<option value="Employee">Employee</option>
<option value="Manager">Manager</option>
</select>
</div>
);
}
}
handleOnChange() is used to change the value upon selection of a different item.
I recommend you use react-select.
const options = [
{ value: '', label: 'Select' },
{ value: 'Employee', label: 'Employee' },
{ value: 'Manager', label: 'Manager' }
];
return (
<Select
name="usertype"
className="form-control"
options={options}
value={this.state.editusertype}
/>
);

REACTJS and ANTD: How to change form contents through <Select> option?

I am new to React and am currently using AntD in my ReactJS code. In my code, I have a select option that is supposed to change the form elements depending on what kind of form it is.
Here is my select:
<Form.Item label="Inquiry Type">
<Select>
<Option>
form 1
</Option>
<Option>
form 2
</Option>
<Option>
form 3
</Option>
</Select>
</Form.Item>
So what should happen is that when I choose Form 1, it should be able to show me all the contents of Form 1, and the same thing for Forms 2 and 3.
I am unsure about how to do this. I have read other questions but they do not answer mine.
Check this.
state = {
selectedForm: "form1"
};
changeForm = value => {
this.setState({
selectedForm: value
});
};
render() {
const { selectedForm } = this.state;
return (
<div>
<Select value={selectedForm} onChange={value => this.changeForm(value)}>
<Option value="form1">form 1</Option>
<Option value="form2">form 2</Option>
<Option value="form3">form 3</Option>
</Select>
{selectedForm === "form1" ? (
<Form1 />
) : selectedForm === "form2" ? (
<Form2 />
) : selectedForm === "form3" ? (
<Form3 />
) : ""}
</div>
);
}

option disabled selected not set as default value in React js dropdown

In the dropdown below, why is Select City not appearing in the dropdown as the default selection on page load ? Instead, City1 appears as the default selected option.
I have the options for default coded as :
<option value="" disabled selected>
Select City
</option>
The options are coded in another js file as below:
import React from 'react'
const cityoptions = [
{ value: '1', name: 'City1' },
{ value: '2', name: 'City2' },
{ value: '3', name: 'City3' },
....
The following is the component for dropdown.
import React from 'react'
import PropTypes from 'prop-types'
import Select from '../others/input/select'
import cityOptions from './city-options'
const InputCities = ({ value, change }) => (
<div className="edit_caste_div">
<Select
placeholder="Select option"
value={value}
valueChange={e => change('city', e)}
className="edit_city my2"
>
<option value="" disabled selected>
Select City
</option>
{cityOptions.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>
})}
</Select>
</div>
)
InputCities.propTypes = {
value: PropTypes.string.isRequired,
change: PropTypes.func.isRequired,
}
You should add a defaultValue attribute to select and set it to the disabled value
<Select
defaultValue="Select City"
valueChange={e => change('city', e)}
className="edit_city my2"
>
<option value="Select City" disabled>
Select City
</option>
{cityOptions.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>
})}
</Select>

Resources