ReactDOM.render not rendering all Id's

Viewed 419

I am trying to create a simple React Chrome Extension and am struggling with some rendering issues. I haven't used vanilla JS in awhile so any help would be appreciated!

I have the following code below that replaces the word 'coronavirus' on any webpage. It also adds id="root" and class="rainbow"(which changes corona virus color) which I hope to render my App component to the id by: ReactDOM.render(<App />, document.getElementById('root'))

replaceText(document.body);
function replaceText(element) {
    if (element.hasChildNodes()) {
        element.childNodes.forEach(replaceText);
    } else if (element.nodeType === Text.TEXT_NODE) {
        if (element.textContent.match(/coronavirus/gi)) {
            const newElement = document.createElement('span');
            newElement.innerHTML = element.textContent.replace(
                /(coronavirus)/gi,
                '<span id="root" class="rainbow">$1</span>'
            );
            const root = document.getElementById('root');
            element.replaceWith(newElement);
        }
    }
}
ReactDOM.render(<App />, document.getElementById('root'));

my simple App component:


class App extends Component {
    render() {
        return (
            <div className="App">
                <h2>Welcome to React</h2>
            </div>
        );
    }
}

export default App;

A quick Google search of 'coronavirus' seems to only successfully render one of my app component. image of google search. When I inspected each coronavirus element it seems that each element has an id="root" and class="rainbow".

Any insight or help would be greatly appreciated!

1 Answers

With current code you are telling react to find the first element with id root and place your component there. ReactDOM.render(<App />, document.getElementById('root'));

You need to tell react that for all elements matching a specific selector, you need to place there your component.

You can try searching by class name and then you need to iterate the ReactDOM.render function.

Check this codesandbox

I guess in your case it would be

const divs = document.getElementsByClassName("rainbow");
for (var i = 0; i < divs.length; i++) {
  ReactDOM.render(<App />, divs.item(i));
}
Related