Reputation: 507
I am doing this:
const changePrice = (event) => {
let {value} = event.target;
priceBook = JSON.parse(value).price
}
return (
<div className="container">
<select onChange={changePrice}>
{planes.map((book, index) => {
return <option key={index} value={JSON.stringify(book)}>{book.pages}</option>
})}
</select>
<span>Price {priceBook} </span>
</div>
);
And it loads the selector values well, but when I change the value I should update the price value in the view, which does not happen.
Upvotes: 2
Views: 451
Reputation: 1014
You need to make a change to the state to trigger a component render. You can do this as answered by @Dupocas or try to use a setState in a class component, like this:
return (
<div className="container">
<select
onChange={(event) => {
let { value } = event.target;
this.setState({
priceBook: JSON.parse(value).price || 0
})
}}
>
{planes.map((book, index) => {
return <option key={index} value={JSON.stringify(book)}>{book.pages}</option>
})}
</select>
<span>Price { this.state.priceBook } </span>
</div>
);
Upvotes: 1
Reputation: 21297
To implement stateful logic inside function based components use hooks
:
const [priceBook, setPriceBook] = useState('such empty')
const changePrice = (event) => {
let {value} = event.target;
const priceBook = JSON.parse(value).price
setPriceBook(pricebook)
}
return (
<div className="container">
<select onChange={changePrice}>
{planes.map((book, index) => {
return <option key={index} value={book.price}>{book.pages}</option>
})}
</select>
<span>Price {priceBook} </span>
</div>
);
Upvotes: 2