Venkat Ch
Venkat Ch

Reputation: 1268

How to render a react component using HTML class attribute?

I tried following but it seems not working. Is this possible to render a react component using HTML class?

HTML

<div class="appKlass"> 
</div>

JSX

ReactDOM.render(
  <h3>Hello Universe</h3>,
  document.getElementsByClassName("appKlass")
)

Upvotes: 0

Views: 410

Answers (2)

hjrshng
hjrshng

Reputation: 1826

It would be cleaner to use document.querySelector('.appKlass'). This will return a single DOM element or null. In case there are multiple .appKlass in the page, it will return the first one.

Upvotes: 1

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

getElementsByClassName returns an array-like object (HTMLCollection) of html elements. But render needs a DOM node as the second argument. So you have to give an index to what returned by getElementsByClassName and get a specific element from the array.

ReactDOM.render(
  <h3>Hello Universe</h3>,
  document.getElementsByClassName("appKlass")[0]
)

Upvotes: 4

Related Questions