Hrusikesh Bunu
Hrusikesh Bunu

Reputation: 71

How to convert react element to HTML

Usage of TestComponent

 <TestComponent
   testContent= {
     <div>
       <p>sometxt <a href="#">link1</a><p>
       <p>hello how was your day</p>
       <p>some other txt <a href="#">link1</a><p>
     </div>
   }
 />

class TestComponent extends React.Component {
  constructor(props) {
    const testContent = props.testContent;
  }
}

In the above component code,In constructor, when i try to access props.testContent. It's type is react element. However i want to query the content to find the focusable elements e:g: in this example. As the prop value is react element querySelector() can not be used. so i need to covert this react element to HTML element.

Could any one help me to know how can i achieve this. Any help is greatly appreciated.

Thanks!

Upvotes: 1

Views: 3710

Answers (1)

Matt Holland
Matt Holland

Reputation: 2210

In your example, there isn't yet an HTML element (aka DOM Node) - this won't exist until the component has been mounted into the DOM. Once that's done you can either use ReactDOM.findDOMNode() (See https://reactjs.org/docs/react-dom.html#finddomnode) or a ref (See https://reactjs.org/docs/refs-and-the-dom.html) to access the element.

You would need to do this step in either the componentDidMount or componentDidUpdate React lifecycle methods. (See https://reactjs.org/docs/react-component.html#componentdidmount)

Upvotes: 1

Related Questions