daniel
daniel

Reputation: 148

Component prop not changing when select value changes

I've got the following code for a SchoolsList component:

import { useSelector } from "react-redux"
import ClassesList from "../classes/ClassesList"

const SchoolsList = () => {
    const schools = useSelector(selectAllSchools)
    if (schools.length === 0) {
        return <h2>No schools created yet</h2>
    }

    let selectedSchool = schools[0]
    const handleChange = (e) => {
        selectedSchool = schools[e.target.value]
        document.getElementById("schoolName").innerText = "Name: " + selectedSchool.name
    }

    return (
        <div className='SchoolsList'>
            <select onChange={handleChange}>
                {schools.map((school, id) => <option key={id} value={id}>{school.name}</option>)}
            </select>
            <h3>Selected school</h3>
            <h4 id="schoolName">Name: {selectedSchool.name}</h4>
            <ClassesList classes={selectedSchool.classes} />
        </div>
    )
}

export default SchoolsList

When the value of the select changes, and the variable selectedSchool changes, the ClassesList component prop isn't updated. I'm pretty new to react-reduce so I'm a bit lost as to what to do. How can I update the value of the prop when the select changes?

Upvotes: 0

Views: 241

Answers (2)

Katongole Richard
Katongole Richard

Reputation: 16

This is there is no re-rendering happening. Try using the useState or useRef hook to store the value of the selected school.

const [state, setState] = useState({
    selectedSchool:''
})

Then save the value of the selected school within state. Use an useEffect to set state with the initial value of school of your choice.

useEffect(()=>{
    setState({...state, selectedSchool:schools[0]})
},[])

Upvotes: 0

Vitaliy Rayets
Vitaliy Rayets

Reputation: 2404

Your variable selectedSchool is not reactive, you can use hook useState and it will be update state in props. Example:

    const [setSelectedSchool, selectedSchool] = useState(schools[0]);
    const handleChange = (e) => {
          setSelectedSchool(schools[e.target.value])
    }

Also you don't need to do this document.getElementById("schoolName").innerText = "Name: " + selectedSchool.name it's incorrect.

You have correct JSX <h4 id="schoolName">Name: {selectedSchool.name}</h4> already

Upvotes: 1

Related Questions