简体   繁体   中英

CSS class only applying to one element

I have some code that unpacks an array and returns an array of JSX elements. This works fine, however, when one element is clicked, the "selectedEl" css class is removed from all other elements.

I'm pretty sure I've just made some stupid mistake but I can't seem to figure it out. Thanks

Code that unpacks the array and assigns onClick method:

function UnpackReccArray() {
        const renderArray = []
        for (let renderEl = 0; renderEl < self.state.capMethod; renderEl++) {
            renderArray.push(
                <span className="topicElement" onClick={self.pushToChosen.bind(this, self.state.reccDataQuery[renderEl].topicID, renderEl + "topicEl")} id={renderEl + "topicEl"}>
                    <p className="fontLibre">{self.state.reccDataQuery[renderEl].displayName}</p>
                </span>
            )
            if (renderEl + 1 === self.state.capMethod) {
                return (
                    <self.ResultRender title="Popular Subjects" renderContent={renderArray} />
                )
            }
        }
    }

Code that handles onClick function

pushToChosen = (id, elID) => {
    const self = this
    const localChoseArray = this.state.subjectChosenArray
    const index = localChoseArray.indexOf(id.toString())
    if (index > -1) {
        localChoseArray.splice(index, 1);
        self.setState({
            subjectChosenArray: localChoseArray
        }, () => {
            document.getElementById(elID).classList.remove("selectedEl")
        })
    } else {
        self.setState({
            subjectChosenArray: [...this.state.subjectChosenArray, id.toString()]
        }, () => {
            document.getElementById(elID).classList.add("selectedEl")
        })
    }
    document.getElementById(elID).classList.toggle("selectedEl")
}

GIF of the code in action

Thanks!

i didn't fully understand the code but it seems that the toggle is what causing the issue since the if and else handles all possible cases, toggle is probably going to do the opposite of the if else bloc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM