Onchange Event Using React Js for Drop Down

OnChange event using React JS for drop down

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:

  • http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html
  • http://facebook.github.io/react/docs/forms.html

React: OnChange for drop down return me the entire select/select tag

What you want is a key/value at select value, but unfortunately, it does not work.
Maybe you'll need to use another component like React-select or use JSON.stringfy() and JSON.parse()

I have made an abstraction code using JSON methods.

const uuid = {
v4() {
return Math.random();
}
};

const users = [
{ name: "All", key: uuid.v4() },
{ name: "Koko", key: uuid.v4() },
{ name: "Krikri", key: uuid.v4() },
{ name: "Kéké", key: uuid.v4() }
];

function App() {
const [selected, setSelected] = React.useState("");

function parseSelected(event) {
const valueToParse = event.target.value;
const itemSelected = JSON.parse(valueToParse);
setSelected(itemSelected);
return;
}

return (
<div>
<select name="any" id="any" onChange={parseSelected}>
{users.map(user => (
<option key={user.key} value={JSON.stringify(user)}>
{user.name}
</option>
))}
</select>
<p>Selected name: {selected.name}</p>
<p>Selected key: {selected.key}</p>
</div>
);
}

the reason is Option HTML interface accepts only DOMString as a value.
You can see the docs here

Passing OnChange Function using React for drop down

There are multiple issue,

  1. In Dropdown component you should add eventListener for onClick not onChange.

  2. Inside handlePaymentImageChange method you are using e.target.value for the value. But in your case e itself is the value. So you should write,

    setPaymentImage({
    ...paymentImage,
    value: e
    });

  3. When you are rendering the image there is no check. So check if value is "Visa" and render visa image and so on.

I have updated the code here please check.

Select value doesnt change the first time I trigger onChange event when using setSate React

The problem is that when you provide onChange prop to select component it become a controlled component.

For more information: React Docs - Forms #controlled components

When you dealing with controlled components you must provide a value to it and when onChange triggerd it should update that value to work properly. Since you did not provide the full code, I imagine you have an array of select menus and options attached to it.

So in this case every select component should have own onChange method and own value to work properly. To achive this we should create another component for only Select Options. Like this;

function SelectComponent({ optionList, onSelected }) {
const [value, setValue] = useState();

const updateValue = ({ target }) => {
setValue(target.value);
if (onSelected) onSelected(target.value);
};

return (
<>
<label htmlFor={optionList.id}>{optionList.label}</label>
<select
id={optionList.id}
name={optionList.name}
value={value}
onChange={updateValue}
>
{optionList.options.map((option) => (
<option value={option.value} key={uuid()}>
{option.text}
</option>
))}
</select>
<button>{optionList.buttonLabel}</button>
</>
);
}

This component accepts to props; optionList and onSelected

optionList is the list of options to render

onSelected is a method that we call when user select and option

On main component, we should change the select section with our select component with props optionList and onSelected

  return (
<div>
{selectMenus.map((select) => (
<div key={select.id} className="select-container">
<SelectComponent optionList={select} onSelected={updateValue} />
</div>
))}
</div>
);

So overall code is like this:

import { useState } from "react";
import { v4 as uuid } from "uuid";

export default function App() {
const [url, setUrl] = useState();

const updateValue = (value) => {
setUrl(value);
};

const selectMenus = [
{
id: 1,
label: "Menu 1",
name: "menu1",
buttonLabel: "Menu 1",
options: [
{
text: "option 1",
value: "option1"
},
{
text: "option 2",
value: "option2"
},
{
text: "option 3",
value: "option3"
}
]
},
{
id: 2,
label: "Menu 2",
name: "menu2",
buttonLabel: "Menu 2",
options: [
{
text: "option 1",
value: "option1"
},
{
text: "option 2",
value: "option2"
},
{
text: "option 3",
value: "option3"
}
]
},
{
id: 3,
label: "Menu 3",
name: "menu3",
buttonLabel: "Menu 3",
options: [
{
text: "option 1",
value: "option1"
},
{
text: "option 2",
value: "option2"
},
{
text: "option 3",
value: "option3"
}
]
}
];

return (
<div className="App">
<h1>URL Value: {url}</h1>
{selectMenus.map((select) => (
<div key={select.id} className="select-container">
<SelectComponent optionList={select} onSelected={updateValue} />
</div>
))}
</div>
);
}

function SelectComponent({ optionList, onSelected }) {
const [value, setValue] = useState();

const updateValue = ({ target }) => {
setValue(target.value);
if (onSelected) onSelected(target.value);
};

return (
<>
<label htmlFor={optionList.id}>{optionList.label}</label>
<select
id={optionList.id}
name={optionList.name}
value={value}
onChange={updateValue}
>
{optionList.options.map((option) => (
<option value={option.value} key={uuid()}>
{option.text}
</option>
))}
</select>
<button>{optionList.buttonLabel}</button>
</>
);
}

Working example is overhere codesandbox

onChange event select in ReactJs

Try this

<Col md={4} className="col-padding-left">
<Input onChange={this.filterProducts.bind(this)} type="select" name="select" id="exampleSelect">
<option name='default'>Default</option>
<option name='price' value='desc'>Price (High-Low)</option>
<option name='price' value='asc'>Price (Low-High)</option>
<option name='addedAt' value='desc'>Added At (First-Last)</option>
<option name='addedAt' value='asc' >Added At (Last-First)</option>
<option name='name' value='desc'>Name (A-Z)</option>
<option name='name' value='asc'>Name (Z-A)</option>
</Input>
</Col>

filterProducts = (e) => {
console.log(e.target.value);
}

In React when in onChange function how to update another custom component's state and pass a value in?

The answer for my question is in the custom component that I wanted to rerender when the drop down ( a different component) is changed is to define the variables that are changing in the custom component DownloadSelector in state (not a local let) such as:

  const [isMyVar] = useState(false);

Then when isMyVar is updated the state changed & the component rerenders. The answer was not (what I originally thought) was to have the code in the onChange event of the 2nd component. I appreciate @Hostek for your help.



Related Topics



Leave a reply



Submit