Count checked checkboxes in React.js

Viewed 8163

I'm using a document structure like this

render() {
return (
    <div className="MyComponent">
        <ul className="">
            {parseRecommendations(this.props.recommendations)}
        </ul>
    </div>
);
}

function parseRecomendations(recommendations) {
    return recommendations.map((recommendation, key) => {
        return (<Recommendation data={recommendation} key={key} />);
    });
}

Where each Recommendation is its own component containing a checkbox

class Recommendation extends Component {
    const recommendation = this.props.data;
    const pageUrl = recommendation.url;

    return (
        <li className="article-item" key={key}>
            <div className="article-info">
                <input type="checkbox" defaultChecked="checked" aria-described-by={recommendation.pii} />
                <a className="journal-title" href={pageUrl} id={recommendation.pii}>{recommendation.title}</a>
            </div>
        </li>
    );

I'd like to have a title saying [Download (x) PDFs], where x is the number of selected checkboxes. How do I find the value of x in this case?

3 Answers

You also could obtain the total of selected checkboxes by element type. The "console.log(totalSelectedCheckboxes)" will print them when the state of totalSelectedCheckboxes change using useEffect Hook.

import React, { useState, useEffect } from 'react';

const RenderCheckboxes = () => {
    const [totalSelectedCheckboxes, setTotalSelectedCheckboxes] = useState(0);
    function handleChk() {
        setTotalSelectedCheckboxes(document.querySelectorAll('input[type=checkbox]:checked').length);
    }
    useEffect(() => {
        console.log(totalSelectedCheckboxes);
    }, [totalSelectedCheckboxes]);
    return (<div>
        <div>
            <input type="checkbox" value={1} onChange={() => handleChk()} />Chk1
        </div>
        <div>
            <input type="checkbox" value={2} onChange={() => handleChk()} />Chk2
        </div>
        <div>
            <input type="checkbox" value={2} onChange={() => handleChk()} />Chk2
        </div>
    </div>);
}
export default RenderCheckboxes;
Related