score:406
the change event is triggered on the <select>
element, not the <option>
element. however, that's not the only problem. the way you defined the change
function won't cause a rerender of the component. it seems like you might not have fully grasped the concept of react yet, so maybe "thinking in react" helps.
you have to store the selected value as state and update the state when the value changes. updating the state will trigger a rerender of the component.
var myselect = react.createclass({
getinitialstate: function() {
return {
value: 'select'
}
},
change: function(event){
this.setstate({value: event.target.value});
},
render: function(){
return(
<div>
<select id="lang" onchange={this.change} value={this.state.value}>
<option value="select">select</option>
<option value="java">java</option>
<option value="c++">c++</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
react.render(<myselect />, document.body);
also note that <p>
elements don't have a value
attribute. react/jsx simply replicates the well-known html syntax, it doesn't introduce custom attributes (with the exception of key
and ref
). if you want the selected value to be the content of the <p>
element then simply put inside of it, like you would do with any static content.
learn more about event handling, state and form controls:
score:0
var myselect = react.createclass({
getinitialstate: function() {
var myselect = react.createclass({
getinitialstate: function() {
return {
value: 'select'
}
},
change: function(event){
event.persist(); //the main line that will set the value
this.setstate({value: event.target.value});
},
render: function(){
return(
<div>
<select id="lang" onchange={this.change.bind(this)} value={this.state.value}>
<option value="select">select</option>
<option value="java">java</option>
<option value="c++">c++</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
react.render(<myselect />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
score:1
thank you felix kling, but his answer need a little change:
var myselect = react.createclass({
getinitialstate: function() {
return {
value: 'select'
}
},
change: function(event){
this.setstate({value: event.target.value});
},
render: function(){
return(
<div>
<select id="lang" onchange={this.change.bind(this)} value={this.state.value}>
<option value="select">select</option>
<option value="java">java</option>
<option value="c++">c++</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
react.render(<myselect />, document.body);
score:2
i'll add this here, in case it helps someone because this was the solution that helped me.
this is to get the selected index. not for the value. (worked for me because my options list was a list of numbers)
const [selectedoption, setselectedoption] = usestate(0)
<select onchange={event => setselectedoption(event.target.options.selectedindex)}>
score:4
if you are using select as inline to other component, then you can also use like given below.
<select onchange={(val) => this.handleperiodchange(val.target.value)} classname="btn btn-sm btn-outline-secondary dropdown-toggle">
<option value="today">today</option>
<option value="this_week" >this week</option>
<option value="this_month">this month</option>
<option value="this_year">this year</option>
<option selected value="last_available_day">last availabe nav day</option>
</select>
and on the component where select is used, define the function to handle onchange like below:
handleperiodchange(selval) {
this.props.handleperiodchange(selval);
}
score:7
handlechange(value, selectoptionsetter) => {
selectoptionsetter(value)
// handle other stuff like persisting to store etc
}
const dropdown = (props) => {
const { options } = props;
const [selectedoption, setselectedoption] = usestate(options[0].value);
return (
<select
value={selectedoption}
onchange={e => handlechange(e.target.value, setselectedoption)}>
{options.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
);
};
score:44
import react, { purecomponent, fragment } from 'react';
import reactdom from 'react-dom';
class select extends purecomponent {
state = {
options: [
{
name: 'select…',
value: null,
},
{
name: 'a',
value: 'a',
},
{
name: 'b',
value: 'b',
},
{
name: 'c',
value: 'c',
},
],
value: '?',
};
handlechange = (event) => {
this.setstate({ value: event.target.value });
};
render() {
const { options, value } = this.state;
return (
<fragment>
<select onchange={this.handlechange} value={value}>
{options.map(item => (
<option key={item.value} value={item.value}>
{item.name}
</option>
))}
</select>
<h1>favorite letter: {value}</h1>
</fragment>
);
}
}
reactdom.render(<select />, window.document.body);
score:72
react hooks (16.8+):
const dropdown = ({
options
}) => {
const [selectedoption, setselectedoption] = usestate(options[0].value);
return (
<select
value={selectedoption}
onchange={e => setselectedoption(e.target.value)}>
{options.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
);
};
Source: stackoverflow.com
Related Query
- OnChange event using React JS for drop down
- React JS: Pass event inside onChange drop down (Ant Design)
- Using Lodash debounce with React useCallback for input onChange event
- How to implement Drop down in React JS using Array for the below snippet of code
- Handling onChange event for MaterialUI drop down element
- onChange event for React child component to update state
- How to simulate mouse over event on a div using enzyme for testing a react application?
- how to get selected value onChange of react redux-form drop down
- Unable to get onDragStart Event on React for HTML5 Drag and Drop
- React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
- React - onChange event for contentEditable attribute
- React Hooks onchange event too slow for scanner input
- React: OnChange for drop down return me the entire <select></select> tag
- How to build a proper onChange event for a controlled React component
- onChange event not firing for input field with React
- React passing onChange event down to child component
- How can I add onClick event for Ref Element using React Hooks?
- Select value doesnt change the first time I trigger onChange event when using setSate React
- May I update state using useRef hook instead of onChange event in React js?
- How to check multiple validations for password conditions based onChange event fired in react js
- OnChange for Storing Value of Selected Drop Down Option
- Why is this is undefined when mocking event in React unit testing, using sinon.spy to mock function and enzyme.shallow render for React Component?
- Reduce lag of displaying value on textfeild when binding onChange event for getting value in React
- Using FullCalendar on React without Jquery UI Draggable for external drag drop
- How to Update JSON Object's state for onChange event in REACT JS?
- How to trigger the onChange event in React after user stops typing for a specified time
- How To Capture OnChange Event Using CKEditor with React JS
- How can I get "useState" to work properly when using event handlers for mouse events witin a React component?
- React - How to pass props down for the .map function when using functional components
- How to get the value from drop down selection using react
More Query from same tag
- Share form data value from child component to parent component - React js
- Checkout flow: how should I process a new order?
- How do i get data from react hook.?
- How to sent parameter in SwipeableDrawer of material ui in reactjs
- How should I use redux with nested subcomponents that won't be reused?
- How can i resolve this error in React+Material UI
- I am trying to display specific data by passing a parameter to a fetch call
- ReactJS: Render an object with keys with map
- Flexbox layout with two columns on desktop and one column on mobile
- Regex to match URL - number at end of string, but also match characters at start of string
- inner <li> onClick doesn't fire
- WordPress Gutenberg-Block Editor component SelectControl: custom event prop
- How to bind multiple onChange callback for different inputs?
- How to add live camera scan with "react-qr-reader" in React App?
- What is the purpose of passing props to a React search bar?
- Guarding against empty nested arrays in state
- React Material UI + Router redirect button
- useState variable is one step behind its assignment
- Make Material-UI InputAdornment Icon only visible when selected?
- How to limit the amount of characters displayed on the table
- ./src/app.js module not found: can't resolve '@material-ui/data-grid' in yyy
- How to know that a onclick event is called from mouseclick or pressing the enter key
- cloning a 2d array using JSON.stringify()
- How to transition scenes with clouds in css js
- Handling clearing a view component in React Or Vuejs
- Issue with routing in react app
- How to get the selected text from text area in react?
- Jest Unexpected identifier: React
- How to get the value of the highlighted item with react-select-plus?
- Can't remove white header in react-data-table-component