Issue
<select>
<option selected disabled>Select</option
I added an extra option with a disabled property, but this gives me the following warning:
Use the
defaultValue
orvalue
props on select instead of settingselected
on option.
<select>
{this.props.optionarray.map(function(e){
return <option
value={e[self.props.unique]}
key={e[self.props.unique]}
>
{e[self.props.name]}
</option>
})}
</select>
optionarray
is an array
which is passed through props
to be mapped on each index which has an object
and I pass the key through props
as well which was in the array. Everything is working here, it's just showing me the warning that I mentioned above.
How do I remove that or how do I set a perfect placeholder for a dropdown in react?
Solution
Reason is, React
provide a better way of controlling the element by using states
, so instead of using selected
with option use the value property of select
and define its value in the state
variable, use the onChange
method to update the state
, Use it in this way:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '1'
};
}
render(){
return(
<select value={this.state.value} onChange={(e)=>{this.setState({value: e.target.value})}}>
<option value='1' disabled>Select</option>
{
[2,3,4].map((i,j)=>{
return <option key={i} value={i}>{i}</option>
})
}
</select>
);
}
}
How to set placeholder for dropdown?
According to Mozilla Dev Network, placeholder is not a valid attribute on a <select>
. So in place of that you can you this also to render a default
option:
<option default>Select</option>
Use of key as per DOC:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
Suggestion:
Whenever we create any ui
dynamically
in loop, we need to assign a unique
key to each element
, so that react
can easily identify the element, it basically used to improve the performance
.
Check the working example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '1'
};
}
render(){
return(
<select value={this.state.value} onChange={(e)=>{this.setState({value: e.target.value})}}>
<option value='1' disabled>Select</option>
{
[2,3,4].map((i,j)=>{
return <option key={i} value={i}>{i}</option>
})
}
</select>
);
}
}
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'/>
Check the fiddle for working example: https://jsfiddle.net/29uk8fn0/
Answered By - Mayank Shukla
Answer Checked By - - David Goodson (ReactFix Volunteer)