ReactJS: Select with default value from props without onChange event? - javascript

So, I was just wondering if I absolutely need to have a onChange event handler on a select component in React?
I have a prop passing in the default value on the option I want selected. It works no problem if I have:
<select
value={this.props.defaultValue}
>
<option value="a">A</option>
<option value="b">B</option>
</select>
Except, it is static as I am sure you are familiar with the error:
Warning: Failed form propType: You provided a `value` prop to a form field without an `onChange` handler.
This will render a read-only field.
As I am getting the value using Jquery, I don't need a state or any passing between child and parent...
Is there a simple way to allow the select to get a default value from props and still operate as a normal select where changing an option changes the value I can grab with jquery, or do I have to have a state, and a onChange handler?
Thanks!
What I have already tried:
<select
defaultValue={this.props.defaultValue} // just returns the first option
>
<options etc.>
</select>
Also, I would rather not use an external package like React-Select... I just want to have a default value and a normal select...

As #julien mentions, you can use ref instead of JQuery to get the current value of the select in an uncontrolled component:
class MySelect extends React.Component {
constructor(props) {
super(props);
this.state = { currentValue: this.props.defaultValue };
}
updateValue() {
this.setState({ currentValue: this.refs.myselect.value });
}
render () {
return (
<div>
<div>
<button className="current" onClick={this.updateValue.bind(this)}>{this.state.currentValue}</button>
</div>
<select ref="myselect" defaultValue={this.props.defaultValue}>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</div>
);
}
}
For the other part, defaultValue should work just as you were trying.
Check this example fiddle: https://jsfiddle.net/y64gbhf8/1/

you can try Uncontrolled Components
you don't need to write event handler for state update,DOM will handle it,
then you can use a ref to get form values from the DOM

Related

How to show placeholder instead of the state's value at pageload?

I am trying to show the placeholder of an input instead of its state value. When I load the page it shows a blank select box, which makes sense because the testType state is null when the page first loads. How can I get it to just show the placeholder instead of the null state?
function RandomSelection(props) {
const [testType, setTestType] = useState(null);
const handleTestType = value => {
setTestType(value);
};
return(
<Select
placeholder="Test Type..."
value={testType}
onChange={handleTestType}
>
<Option value="Option 1">
Option 1
</Option>
<Option value="Option 2">Option 2</Option>
<Option value="Option 3">Option 3</Option>
</Select>
) }
The Select option is from Ant Design, however I feel the solution to this may apply to Material-UI and Bootstrap as well.
Since you never show the import path, and your code works perfectly fine using Antd's Select, my guess is that you're using the Select from MUI (partly because you also tagged material-ui in your question). So check your import path, because MUI Select placeholder is set by the label prop:
Right
import { Select } from 'antd';
Wrong
import { Select } from '#mui/material';
In const [testType, setTestType] = useState(null);, set useState's default value to what you want the placeholder to be instead of null.

How to pass the value of a component up to its parent?

I want to bind the value of a select element in a Svelte component (Form.svelte) to the variable active in its parent (App.svelte). I've tried using bind:value={active} on the Form component in App, but this doesn't work because I need to access the select's value. How should I access the value of the select element? Thanks in advance.
Minimum working example: https://svelte.dev/repl/bc872132e21f4071abe5a255728fb0ec?version=3.43.0
You need to expose the value property if you want to bind to it. Here, we also bind the value property to the select element so that it is updated with changes to the select.
/* Select.svelte */
<script>
export let value
</script>
<select bind:value>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
You can then bind to it in your parent
/* App.svelte */
<script>
import Select from './Select.svelte'
let active;
</script>
<Select bind:value={active}/>
<p>{active}</p>
REPL

select method to restore to default value

Iam trying to do something that look easy but i cant find any soulotion,
i have <select> tag with 5 <option> all i want to do is when i click a button (have function inside of it) the select tag will be the default one (the first one)
for example :
<select className={'smallSelect'} onChange={appliances}>
<option defaultValue =''>Add</option> {/* The default */}
<option value='<Fan/>'>Air-Conditioner</option>
<option value='<HotTub/>'>boilermaker</option>
<option value='<Bulb/>'>lamp</option>
<option value='<Radio/>'>stereo system</option>
</select><br/> {/* After clicking the button the option will be the default */}
<button className={'myButton'} onClick={newAppliances}>Add</button>
I assume the button onClick event calls the function newAppliances?
You need to set the select value to ''. So add something like this at the end of your newAppliances function.
document.getElementById('.smallSelect').value = '';
See this:
How do I programmatically set the value of a select box element using JavaScript?
For React
The above solution is for normal javascript, if you want to do the react way, read this:
React JSX: selecting "selected" on selected <select> option

angular 2 select element trigger onchange

I have a select element defined as follows:
<form #empForm="ngForm" novalidate>
<div>
<label>Role</label>
<select name="role" [(ngModel)]="user" (ngModelChange)="get1($event)" (change)="get($event)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
</form>
And in the .ts,
Since the select html is bounded to the property user, setting it to different values programmatically as follows does not trigger the ngModelChange or change event which i believe is triggered solely based on user intervention
set(input: any) {
this.user = "3";
}
I wish to trigger those events when the model changes programatically. Is that possible?
Thank you,
Ashley
Try adding value Attributes like <option value="1">
When the page loads and you set the default value, take it from there and do the logic. No need to read it via your element after you set it.

why does ReactJS suppress changes in <input> elements but not in e.g. <select> elements

Here's a SSCCE to illustrate my question:
const React = require('react');
const App = React.createClass({
getInitialState: function() {
return {
text: 'foo',
selection: 'apples'
};
}
, render: function() {
return (
<div>
<div>
<input type='text' value={this.state.text}/>
</div>
<select>
<option value='bananas' selected={this.state.selection==='bananas'}>bananas</option>
<option value='apples' selected={this.state.selection==='apples'} >apples </option>
<option value='onions' selected={this.state.selection==='onions'} >onions </option>
</select>
</div>
);
}
});
The above React component when rendered, displays (unsurprisingly) the below view:
The model is taken into account as expected.
When one tries to type into the <input> element nothing happens. The explanation is that ReactJS uses one way flow and you have to add onchange listeners to update the model etc. That's fine.
What I don't get is why ReactJS prevents the <input> element from changing and forces it to always reflect the model value that flowed down to it, whereas at the same time it allows me to change the <select> element:
Apparently my mental model is lacking. What am I missing ?
You're hard coding the value to be this.state.text so it will always be the same on every keystroke. See the forms documentation.
What you have here is a controlled <input> element and an uncontrolled <select> element. See controlled components
Its possible to create an uncontrolled text input by not specifying the value prop.
And its possible to create a controlled select element by specifying the value prop.
<select value={this.state.value}>
<option value="bannanas">bananas</option>
<option value="apples">apples</option>
<option value="onions">onions</option>
</select>
There is documentation explaining specifically this. See here

Categories

Resources