In my react app i have an endpoint that returns user details and another on that returns countries and I'm calling both of them in the componentDidMount, i have a country dropdown and it's default value/option should be the country returned from the user details endpoint and it's options should be the countries list returned from the countries endpoint, the problem is when i use the value attribute to set the default value for the select it's always null and it doesn't show a value, so i tried using the <option selected="selected">{this.state.country}</option> but the onChange function doesn't work when i use it, so what's the best approach to achieve that, here is the code:
Using the value attribute:
<select value={this.state.country} onChange={this.handleChange}>{this.renderCountries()}</select>
Using the selected option:
<select onChange={this.handleChange}>
<option selected="selected">{this.state.country}</option>
{this.renderCountries()}
</select>
OnChange function:
handleChange = event => {
this.setState({ selectedOption: event.target.value });
};
Rendering options:
renderCountries() {
return this.state.countries.map(country => (
<option key={country.id} value={country.id}>
{country.name}
</option>
));
}
Set this.state.country to the value returned from the endpoint.
<select value={this.state.country} onChange={this.handleChange}> .
{this.renderCountries()}
</select>
The handleChange needs to setState for country not selectedOption. This is because the value attribute on select is this.state.country
handleChange = event => {
this.setState({ country: event.target.value });
};
renderCountries = () => {
return this.state.countries.map(country => (
<option key={country.id} value={country.id}>
{country.name}
</option>
));
};
Hopefully this should fix your issue.
Related
I have a list of option, I'm getting from the API. I'm using .map() and When I change the option I want the specific option object so I can store that inside of redux store.
<select
onChange={() => handleChange()}
className="pl-2 bg-white font-medium border-none"
>
{outlets.map((outletItem) => (
<option key={outletItem.outlet_id} value={outletItem.outlet_id}>
{outletItem.name}
</option>
))}
</select>
Here, outlets is an array from the API. I want the specific value of the array when I make a change.
handleChange()
const handleChange = () => {
dispatch(addSelectedOutlet(outlets));
};
You need to catch the value of onChange
onChange={(e) => handleChange(e)}
then
const handleChange = (e) => {
console.log(e.target.value)
};
Iam trying to create a dropdown component and would like to use that selected option through out my app.
The thought is when a user select a Dropdown value then, its state got save in Redux reducer then to use that value for other action. But being a beginner Iam stuck on implementation part.
Note: The dropdown wouldnt have a submit button, just the action of selecting the drop down option.
My code until this stage looks like this:
RoleDropdown.js
class RoleDropdown extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
...
...
render() {
return (
<div>
<select
onChange={() => this.props.selectedRoleAction()}
name="roles" className="form-control">
<option>Select a Role</option>
<option value="ABC" >ABC</option>
<option value="DEF" >DEF</option>
<option value="GHI" >GHI</option>
</select>
<p>role is: {this.props.activeRole.value}</p> //No value output here
</div>
)
}
SelectedRoleAction.js
const selectedRoleAction = (role) => {
const [value, setValue] = useState("")
setValue({ value: role.target.value })
console.log("event from drop down is " + role) //I cant see any logged value as well
return {
type: "ROLE_SELECTED",
payload: role,
}
};
Where Am I doing wrong? Does the "setValue" can be used in action reducers?
An action creator does not hold any local state. It is just a function that maps from some arguments to a Redux action which is an object with properties type and payload.
This is an action creator function:
const selectedRoleAction = (role) => {
return {
type: "ROLE_SELECTED",
payload: role,
}
};
In which case your component would call:
onChange={(e) => this.props.selectedRoleAction(e.target.value)}
You are trying to map from the event to the value in the action creator rather than in the component. This is unusual and I would recommend the above approach, but it's doable.
const selectedRoleEventHandler = (event) => {
return {
type: "ROLE_SELECTED",
payload: event.target.value,
}
};
In which case your component would call:
onChange={(e) => this.props.selectedRoleEventHandler(e)}
or just:
onChange={this.props.selectedRoleEventHandler}
Right now you are calling the function with no arguments this.props.selectedRoleAction() which will not work.
That just creates the action. I'm assuming that you are using the connect higher-order component so that calling this.props.selectedRoleAction will dispatch it to Redux.
The actual state is set through your Redux reducer function.
If the value is stored and updated through Redux then it should not also be in the component state.
You are dealing with a controlled component so you'll want to set the value property on your select.
I am disabling "Select a Role" and also giving it a value of the empty string "". I am using that value as a fallback if this.props.activeRole is not set.
<select
name="roles"
className="form-control"
value={this.props.selectedRole || ""}
onChange={(e) => this.props.selectedRoleAction(e.target.value)}
>
<option value="" disabled>Select a Role</option>
<option value="ABC">ABC</option>
<option value="DEF">DEF</option>
<option value="GHI">GHI</option>
</select>
Inside my render I have a select, and for the options I use a .map, like this:
<select value={this.state.eixo} onChange={this.handleChange}>
<option value=""></option>
{this.state.eixos.map((item) => {
return <option key={item.id}>{item.descricao}</option>
})}
</select>
And I want the key from the option that I choose in my handleChange method, I tried something like this but it doesn't seem to be working:
handleChange = (event) => { this.setState({ key: event.target.value }) };
One way to do it is to Set the value of the option to a key:value pair,
<select value={this.state.eixo} onChange={this.handleChange}>
<option value=""></option>
{this.state.eixos.map(item => {
return (
<option key={item.id} value={`${ite.id}:${item.descricao}`}>
{item.descricao}
</option>
);
})}
</select>;
Then split the e.target.value to get the key : value pair and update the state using bracket notation :
handleChange = event => {
const [key, value] = event.target.value.split(":");
this.setState({ [key]: value });
};
If your values could contain : , choose another seperator.
I need to display some attribute of an element in a select, and store the displayed attributes in a value and a different attribute of the same element in another value.
render() {
const refertiItems = this.state.referti.map((referti, i) => {
return (
<option key={referti.hash_referto}>
{referti.tipo_esame}-{referti.data_esame}
</option>
)
});
return(
<Label for="type" text="Descrizione Referto" />
<select
name="descrizioneReferto"
placeholder="Selezionare Referto"
onKeyPress={this.onEnter}
value={this.state.referti.descrizioneReferto}
onChange={this.handleInputChange}
>
<option default value="vuoto"></option>
{refertiItems}
</select>
So in this code i can store {referti.tipo_esame} and {referti.data_esame} in descrizioneReferto. I also need to store {referti.hash_referto} inside codiceReferto. Any advice?
You can access the key of the option element in the onChange function like this:
handleInputChange = (event, child) => {
this.setState({
descrizioneReferto: event.target.value,
codiceReferto: child.key
});
}
To use the material-ui select, change your code to:
<Select
value={this.state.referti.descrizioneReferto}
name="descrizioneReferto"
onKeyPress={this.onEnter}
placeholder="Selezionare Referto"
onChange={this.handleInputChange}>
<MenuItem value="vuoto"/>
{refertiItems}
</Select>
and
const refertiItems = this.state.referti.map((referti, i) => {
return <Menu key={referti.hash_referto}>
{referti.tipo_esame}-{referti.data_esame}
</option>
});
I have a select with options and want to get the value of the option without submitting a form or using button or input.
for example, if I choose USD I want the function return USD,
for EUR, should return EUR
<select value={this.state.value} onChange={this.handleChange}>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
<option value="RUR">RUR</option>
<option value="GBP">GBP</option>
</select>
<select value={this.state.value} onChange={this.handleChange}>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
<option value="RUR">RUR</option>
<option value="GBP">GBP</option>
</select>
You can access to the selected value inside handleChange like so:
handleChange(e) {
console.log(e.target.value); // for ex. will print USD
}
create a function displayUsd() then in the onChange event of the select element use
this.displayUsd.
You can do something like this in onChange={this.handleChange}
handleChange = (e) => {
// e.target.value will USD
}
or
handleChange: function(event){
// event.target.value
}
assuming you are using a class here and extending react.
constructor() {
this.state = { value: 'default Value' }
}
this.handleChange(e) {
this.setState({ value: e.target.value});
}