My search component returns a mapped list of results based on the input. Depending on the list element clicked, I want to assign it to my current stock state but I am not sure how I would access that specific element.
const selectStock = ()=>{
setSearch("");
setCurrentStock();
}
return (
<div className="searchContainer">
<form className="searchBar">
<input
className="search"
type="text"
placeholder="Search Ticker Symbol"
onChange={handleSearch}
/>
</form>
<div className="searchResults">
<ul>
{/* {stockNames.map((stockname) => {
const { name, symbol} = stockname;
return (
<li className="displaySearch" onClick={selectStock} key={symbol}>
<p>{name} ({symbol})</p>
</li>
);
})} */}
</ul>
</div>
</div>
);
}
CodePudding user response:
First, you'll want to change your selectStock
function to accept the stockName
to which it should be set. That should be passed to your setCurrentStock
function:
const selectStock = (nextStock) => {
setSearch("");
setCurrentStock(nextStock);
}
Then, pass an arrow function through to the onClick
function for the row that you select:
<div className="searchResults">
<ul>
{stockNames.map((stockname) => {
const { name, symbol } = stockname;
return (
<li className="displaySearch" onClick={() => selectStock(stockname)} key={symbol}>
<p>{name} ({symbol})</p>
</li>
);
})}
</ul>
</div>
What this does is essentially create a new function for each row that's specific to itself. When that row is clicked, it triggers its own unique onClick
, which passes its own stockname
value through to selectStock
.
CodePudding user response:
You can pass the selectedStock into the selectStock function by making it a ES6 function.
See below:
const selectStock = (selectedStock)=>{
setSearch("");
setCurrentStock(selectedStock);
}
return (
<div className="searchContainer">
<form className="searchBar">
<input
className="search"
type="text"
placeholder="Search Ticker Symbol"
onChange={handleSearch}
/>
</form>
<div className="searchResults">
<ul>
{/* {stockNames.map((stockname) => {
const { name, symbol} = stockname;
return (
<li className="displaySearch" onClick={()=>selectStock(stockName)} key={symbol}>
<p>{name} ({symbol})</p>
</li>
);
})} */}
</ul>
</div>
</div>
);
You can pass other variables in the similar way if required.