Stanley
Stanley

Reputation: 2816

Replacing custom html tags in react

Have the following code in public/index.html

<body>
    <some-tag><some-tag>
    <script type="text/javascript">
        var obj1 = document.getElementsByTagName('some-tag')[0];;
        obj1.innerHTML = 'abc';
    </script>
</body>

This renders abc into some-tag successfully if i just run index.html alone

However if I use React, i.e.

public/index.html

<body>
    <div id="root"></div>
    <script type="text/javascript">
        var obj1 = document.getElementsByTagName('some-tag')[0];;
        obj1.innerHTML = 'abc';
    </script>
</body>

and React component

class Abc extends Component {
   render() {
       return (<some-tag />)
   }
}

and index.js

ReactDOM.render(
  <Abc />
  document.getElementById('root')
);

It fails to manipulate the tag and show 'abc'. What is the problem?

Upvotes: 3

Views: 1155

Answers (1)

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15841

The problems are various.

First when

  var obj1 = document.getElementsByTagName('some-tag')[0];;

is executed there is not guarantee both that DOM is actually loaded and then that React has actually rendered the html of the component.

Second issue is that modify the react generated html is possible but it is an anti-pattern.

If you want to modify the behaviour of your rendering you have to act on react's components, if the parameter comes from a server/backend what you are you looking for is Server Side Rendering (SSR).

Upvotes: 2

Related Questions