So usually there are really easy ways to avoid mutating your DOM directly from React but unfortunately I'm not in one of those situations right now. I'm using an API that then embeds a lot of content on to my page into a div with an id of dashboard.
I need to manipulate the content on the page and move certain elements around and things. Currently I add an event listener to an element that exists before I call the API, with useEffect() like so:
useEffect(() => {
/*
Some code here...
*/
const setupDashboard = (dashboard) => {
document.querySelector('#run').addEventListener('click', () => {
dashboard.send('dashboard:run')
console.log("Run clicked")
})
console.log(document.querySelector("[data-title='States']"))
}
LookerEmbedSDK.createDashboardWithId(114)
.appendTo('#dashboard')
.on('dashboard:run:start',
/*() => updateState('#dashboard-state', 'Running')*/
)
.on('dashboard:run:complete',
/*() => updateState('#dashboard-state', 'Done')*/
)
.build()
.connect()
.then(setupDashboard)
.catch((error) => {
console.error('An unexpected error occurred', error)
})
});
The piece of code that adds the event handler to the button works, but the next console statement returns null. So it seems like there should be a better way to manipulate the DOM especially since I'm going to completely change it with all my modifications. I'll need to use all sorts of query selectors, deletions, appending and more. What's the best practice for all that.
Edit: to be clear, after the page loads if I run that line in the console it gets the element
I found the answer to my particular situation. In my case, the second query selector doesn't work because the embedded element is in an iframe that represents a second document and is therefore inaccessible.
However, if you're working with react and you need a way to mutate the DOM might I suggest using
ReactDOM.shouldComponentUpdate = () => false
found in this article https://www.reddit.com/r/reactjs/comments/2riuwa/mutating_reacts_dom/