Search code examples
javascriptreactjsreact-bootstrapcustom-element

Passing data to custom elements with React Bootstrap


I have a custom styled checkbox and that checkbox is included in a set of mapped data array.

{nfcArray && nfcArray.map((item, key) => {
     return (
          <tr class="hover">
             <td className="cell_style pl-3 pl-lg-5">
                <Row noGutters>
                    <Form.Check
                       required
                       name={item.cardId}
                       id={item.cardId}
                       as={customCheckBox}
                    />

                    <label>{item.cardId}</label>
                </Row>
            </td>
            <td className="cell_style pl-3 pl-lg-5">{item.name}</td>
          </tr>
      )

 })}

My customCheckBox is given inside the render method like follows

        const customCheckBox = React.forwardRef(
            () => {

                return (
                    <div class="custom-control custom-checkbox my-1 pl-0" >
                        <input type="checkbox" className="custom-control-input" id="" />
                        <label className="custom-control-label" for=""></label>
                    </div>
                );
            },
        );

I want to pass item.cardId to my custom element so i can use item.cardId as id for the checkbox input in the custom element. How can i do this action? Is there a way to pass the item.cardId from as={customCheckBox}


Solution

  • Any props that are unknown to React-Bootstraps Form.Check and CheckInputComponents will be passed along to your customCheckBox Component. Try something like cardId={item.cardId} as additional prop for Form.Check:

    <Form.Check
       required
       name={item.cardId}
       id={item.cardId}
       as={customCheckBox}
       cardId={item.cardId} />
    
    const customCheckBox = React.forwardRef((props) => {
        return (
            <div class="custom-control custom-checkbox my-1 pl-0" >
            <input type="checkbox" className="custom-control-input" id={props.cardId} />
            <label className="custom-control-label" for=""></label>
            </div>
        );
    });