Hi i want to do something when mi select box changes, i have something like this:
function Task(){
const prints = (e) =>{
console.log("it prints");
}
const prints2 = (e) =>{
console.log("it prints2");
}
return (
<select onChange={prints} onClick={prints2} name="subject">
{subjectsContext.subjects.map((aSubject)=>(
<option value={aSubject.idsubject}>
{aSubject.subjectname}
</option>
)
)}
</select>
)
}
subjects is a list that i have, when i put onClick instead of onChange it works fine, but when i put onChange it dont works when i select a option, it just dont trigger the prints function, why?
You need to pass the event (e) to the function as a parameter, try this:
function Task() {
const prints = (e) => {
console.log(e.target.value);
console.log('it prints');
};
const prints2 = (e) => {
console.log(e.target.value);
console.log('it prints2');
};
return (
<select
onChange={(e) => prints(e)}
onClick={(e) => prints2(e)}
name='subject'
>
{subjectsContext.subjects.map((aSubject) => (
<option value={aSubject.idsubject}>{aSubject.subjectname}</option>
))}
</select>
);
}
Also - consider adding a key attribute to you option as you're mapping trough it and creating duplicate elements in the DOM, I assume this is a react app so it might cause errors.
Edit: ... And you don't need the onClick here, you won't even get an event so simply remove it.