0

I have a table component( external library ) and i want to add click event listener to table cells, so that i can copy the table cell content, this is the code i tried

componentDidMount(){
    
    let tableCells = document.getElementsByClassName('Table__cell');
    for (let i = 0; i < tableCells.length; i++) {
        console.log(tableCells[i]);
        tableCells[i].addEventListener('click', () => {
            console.log(i);
        }, false);
    }
}

i know that this is not working because the collection length is 0 even though we have the collection. what is the solution for this ?

1 Answer 1

1

componentDidMount fires long before the DOM is rendered, so the elements don't exist in the DOM.

Mixing classic DOM and React is, however, generally a nightmare and you'll get all sorts of issues as the DOM mutates.

Use event bubbling instead.

const handler = event => console.log(event.target.textContent);

return <div onClick={handler}><ThirdPartyTableComponent /></div>

If the cells contain elements you might need to make your logic a bit smarter and search up the DOM tree via parentNode until you find a table cell (so you get all the content in the table cell and not the content of, for example, a span inside a cell).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.