Here's my code:
function Component(props) {
const [message, setMessage] = useState({
type: "",
text: "",
});
return (
<div>
<select
onChange={(ev) => {
setMessage({ type: **CAN SOMETHING GO HERE???**, text: ev.target.value });
}}
required
>
<option value="Ask a question" **DIFFERENT ATTRIBUTE TO SET TYPE WITH???**>Question</option>
<option value="Leave a comment">Comment</option>
<option value="Voice a concern">Concern</option>
</select>
</div>
);
}
export default Component;
Is it possible to somehow have another value or something similar in my options
so that I can set both the type and text from the same onChange
function? I'm not sure how else to do it and I need both a type and a text for a message to work.
CodePudding user response:
As @DCR's linked question notes, you can use data-
attributes to store your data and read them with the dataset
property, like this:
function Component(props) {
const [message, setMessage] = useState({
type: "",
text: "",
});
return (
<div>
<select
onChange={(ev) => {
let selected = ev.target[ev.target.selectedIndex];
setMessage({ type: selected.dataset.type, text: ev.target.value });
}}
required
>
<option value="Ask a question" data-type="negative">Question</option>
<option value="Leave a comment" data-type="positive">Comment</option>
<option value="Voice a concern" data-type="negative">Concern</option>
</select>
</div>
);
}
export default Component;
You need the ev.target[ev.target.selectedIndex]
part because ev.target
is the <select>
element but you need to get the selected <option>
element from inside it.
(Since you did not say how you plan to use this type
data, I made up an example that it will say whether the feedback is positive
or negative
. This is just an example.)