2

I am using react with typescript and would like to iterator an element and add a unique ref to each element to check if the checkbox element is selected or not.

  private product1Ref: HTMLInputElement;
  private product2Ref: HTMLInputElement;
  private product3Ref: HTMLInputElement;
  private product4Ref: HTMLInputElement;

const listItem: JSX.Element[] = [];
 this.props.products.forEach((ele) => {
  if(ele.isAvailable) {
        listItem.push(
            <li>
                <label>
                    <input
                        type="checkbox"
                        id={ele.name}
                        ref={(input) => ?????? = input}
                    />
                        {ele.name}
                    </label>
            </li>
        );
    }
});

Now is it possbile to add ref to the above elements? if so how can we do it ? If not what is the another way to check if the checkbox element is selected or not?

0

1 Answer 1

0

I'd extract the part that needs a ref into a component:

function Checkbox({id, label}) {
    const [checked, setChecked] = useState(false);
    const onChange = useCallback(e => {
        setChecked(e.target.checked);
    }, []);
    return (
        <label>
            <input
                type="checkbox"
                id={id}
                checked={checked}
                onChange={onChange}
            />
            {label}
        </label>
    );
}

then use that component:

const listItem: JSX.Element[] = [];
this.props.products.forEach((ele) => {
    if(ele.isAvailable) {
        listItem.push(
            <li>
                <Checkbox id={ele.name} label={ele.name} />
            </li>
        );
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.