0

str = "<p> this is paragraph </p>"

The above str can consist of any elements of HTML. So to get he text I have used the below code in my react application.

let descriptionDiv = document.createElement('div');
descriptionDiv.innerHTML = description;
description = descriptionDiv.textContent || descriptionDiv.innerText;

Do I need to use ReactDOM in this scenario ?

Like: React.createElement('div');

But I don't know whether when to use it ? Is it safe to accessing dom directly?

vikas95prasad
  • 1,234
  • 1
  • 12
  • 37
  • I didn't understand your final desire but I guess you can do all of those things with React without reaching the DOM like this. – devserkan Nov 22 '19 at 12:26
  • I have a string that contains HTML tags. I need to read the text from that. I tried it using regex but, sometimes the text is not readable. That's why I'm doing this ? Is this not a recommended method ? – vikas95prasad Nov 22 '19 at 12:30
  • 1
    Something like that maybe? https://stackoverflow.com/questions/39758136/render-html-string-as-real-html-in-a-react-component – devserkan Nov 22 '19 at 12:40

2 Answers2

1

JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI In html it's just creating another node to dom.

If you want to access dom while using react you can use ref

To access the DOM pass a ref with the react element and latter access it with findDOMNode method

It's completely safe to use dom api directly but it depends what is your requirement... simple or you have some complicated tasks ,prefer to use ref in react

example

import ReactDOM from 'react-dom';

...  

let reactElement = ReactDOM.findDOMNode(this.refs.refName)

...  

<Component ref='refName'/>
shashi kumar
  • 362
  • 2
  • 9
-1

React.createElement

React.createElement(
    "button",
          {
            className: "panel-btn-open"
          },
    "Open"
),

document.createElement

 const buttonOpen = document.createElement('button');
 buttonOpen.classList.add('panel-btn-open');
 buttonOpen.textContent = 'Open';