Azu
Azu

Reputation: 1550

React: how to select multiple HTML items within the same component?

I have a simple component with many divs. Some of them have class="sum". How can I select them?

const MyComponent = () => {
    return (
        <div className="container">
            <div></div>
            <div className="sum"></div>
            <div></div>
            <div></div>
            ...
            <div className="sum"></div>
            <div className="sum"></div>
        </div>
    )
}

I know that document.querySelectorAll is not an option. If div.sum were one or two, I could use ref, but in this case I don't know what to do. Thank you.

Upvotes: 1

Views: 1029

Answers (1)

Steve
Steve

Reputation: 8839

There are worse ways to solve this than using querySelectorAll. Since you haven't said why you don't want querySelectorAll, I'm going to provide a solution using it.

const MyComponent = () => {
    const ref = useRef(null);

    // NOTE: Change list deliberately omitted so this runs after
    //       every render is applied to the DOM.
    useEffect(
        () => {
            const sumDivs = ref.current
                ? [...ref.current.querySelectorAll(':scope > .sum')]
                : []

            // TODO: Do something with sumDivs
        }
    )

    return (
        <div ref={ref} className="container">
            <div></div>
            <div className="sum"></div>
            <div></div>
            <div></div>
            ...
            <div className="sum"></div>
            <div className="sum"></div>
        </div>
    )
}

Upvotes: 1

Related Questions