get the value from select option inside <li> react - reactjs

I have multiple select options based on the database all are displayed inside a li tag in the following format.
<ul>
here select options are rendered in a for loop;
<li>
<select>
<option value='xxx'></option>
<option value='yyy'></option>
</select>
<button
onClick={set(selectedvalue)}
>
set
</button>
</li>
</ul>
each li will have an seperate set button how do i pass the selected value to the function.i cant use the useState since it may have many li.

This can be achieved using useRef then getting the value from the reference to the select select. You will pass the ref into the set function and that should allow you to grab the value through current:
import React, { useRef } from "react";
const SelectExample = () => {
const select1 = useRef(null);
const set = (setRef) => {
console.log(setRef.current.value);
};
return (
<ul>
here select options are rendered in a for loop;
<li>
<select ref={select1}>
<option value="xxx"></option>
<option value="yyy"></option>
</select>
<button onClick={set(select1)}>set</button>
</li>
</ul>
);
};
export default SelectExample;

useRef() is certainly one way to get this done.
The first thing you want to do is create a ref to tie to your select:
const selectRef = useRef();
Then link up the select element to the ref like so:
<ul>
<li>
<select ref={selectRef}>
{ar.map((i, index) => (
<option key={index} value={i}>
option {i}
</option>
))}
</select>
<button onClick={() => set(selectRef.current.value)}>set</button>
</li>
</ul>
As you can see, the button will grab the current value of the select and send it to your set function.
<button onClick={() => set(selectRef.current.value)}>set</button>
Here is a Sandbox for you to demonstrate the idea: https://codesandbox.io/s/dark-framework-xuhxn?file=/src/App.js

Related

onClick DOM event inside an option field doesn't work in the Chrome browser

Here's a breakdown of the problem,
I'm calling the setItem function to set the state of an item in an option field element after an item in the current option is clicked with the onClick event, like so
<select>
{items.map((singleItem) => (
<option key={singleItem.id} onClick={() => setItem(singleItem.name)}>
{singleItem.name}
</option>
))}
</select>
<h4>{itemSelected}</h4>
Here's where we have the item state and the setItem function with a useEffect to set the first item name as the default itemSelected
const [itemSelected, setItem] = useState("")
useEffect(() => {
setItem(items[0].name)
}, [])
This works code works as I expect it to on Firefox but the onClick event in the option field doesn't work in Chrome. How could I go about making it work on the two browsers mentioned above?
Here's a sandbox with running code
https://codesandbox.io/s/stoic-hermann-bw83hj
onClick on <option> element is non-standard, please use onChange on <select> like this:
<select onChange={(event) => setItem(event.currentTarget.value)}>
{items.map((singleItem) => (
<option key={singleItem.id}>
{singleItem.name}
</option>
))}
</select>

Why is selected not an option for React?

I am having issues correcting mysyntax in a React project. I get the error "Warning: Use the defaultValue or value props on instead of setting selected on ." However, I am unable currently to dynamically update the selected option for the drop down menu using just value/default value. The code updates 'correctly' when selected is used.
Relevant code below:
const Client = ({..., reactions}) => {
...
List Generator
function ReactionList() {
// retrieve and filter reactions
const availableReactions = reactions.filter(...)
return (
availableReactions.map((reaction, index) =>
<option key={index} value={reaction._id} selected={chosenReaction.name === reaction.name}>
{reaction.name}
</option>
)
)
}
// selecting reaction from drop down
function SelectReactionOption(entry){
setSelectedReactionId(entry);
setReactionPsiUpcast(0);
}
return (
...
<div className="DropDown">
<div>
<p>
Actions:
</p>
<select type="number" name={chosenAction.name} onChange={e => SelectActionOption(e.target.value) }>
<ActionList/>
</select>
</div>
</div>

How can I pass the value of my selected item into the value of input field

I have fetched data items in my search component, but I would like to be able to click on searched item and the value would automatically be printed in my input field. For now I am only able to search and get the results, but nothing is happening when I am clicking on the specific searched item.
Example:
I am searching for country -> I'll write into my input "Cam" -> now my filtered data are coming up and giving me my suggestions -> Cambodia, Cameroon -> I click on Cambodia and in input field I can see value of Cambodia
As I said, my filtering works fine, I just need to be able to pass the value from clicked item to input field
const [search, setSearch ] = useState(undefined);
const handleChange = (e) => {
setSearch(e.target.value)
}
<input type="text" onChange={handleChange} value={search} />
{filteredData &&
filteredData.map((data, index) => (
<li key={`index${index}`}>
<div className="col-6 text pt-2">
<h5>{data.name}</h5>
</li>
))}
I am already passing in input value={search}, but I probably also have to set up something in my list of items - <li tag.
Just set the state in the onClick handler of li:
<li key={`index${index}`} onClick={()=>{setSearch({data.name})}}>
You missed an onClick event handler from list li item.
<input type="search" value={searchItem} onChange={handleChange} />
<ul>
{listData.map((x,i) => (
<li key={i} onClick={handleClick}>{x}</li>
))}
</ul>
Searched Result = > {clickedText}
</div>
Running Example - https://codesandbox.io/s/stackoverflow-react-65754485-oih9d?file=/src/Search.js:666-918

Add css class onClick to idividual elements generated by mapping an array in React

<div className="sub-nav">
<ul>
{props.data.map((item, index) => {
return (
<li key={index} className="sub-nav-item" >{item.name} </li>
);
})}
</ul>
</div>
Hi! I want to add an active class to an individual li when clicked, but I cannot seem to get it to work on mapped elements without adding it to all of them. This is part of a menu component in a React project. Thanks!
The following is hooks implementation.Incase you're using class I think you can derive from the same.
const [selectedItemIndex,setSelectedItemIndex] = useState(null);
<div className="sub-nav">
<ul>
{props.data.map((item, index) => {
return (
<li key={index} onClick={()=>setSelectedItemIndex(index)} className={`sub-nav-item ${selectedItemIndex===index?'active':''}`} >{item.name} </li>
);
})}
</ul>
</div>

Get value of loop options in React

I am looping through an array of objects that return option inside a select tag. As far as I know, I can't attach event handler on the option tag, so I attached onChange handler on select tag. I can get the value of option tag by default, but as I am looping array of objects, I want to get some other values of the object as well. How do I achieve that?.
Here's the snippet of what I am doing,
<select onChange={handleChange}>
{data.map(item => {
return (
<option key={item.id} value={item.name}>
{item.name}
</option>
);
})}
</select>
How do I get for example item.age and item.address when onChange get invoked ?
I find the solution, I set the value of option tag as an object, stringify it using JSON.stringify() so I can get the whole object, and then just read it with JSON.parse()
<select onChange={handleChange}>
{data.map(item => {
return (
<option key={item.id} value={JSON.stringify(item)}>
{item.name}
</option>
);
})}
</select>

Resources