Convert String in React Components Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Convert String in React Components without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a string which is actually a nested react components name with its props. Want to render that string inside another react component . For example

var String = "<parentComponent title='Parent'><childComponent age='23'></childComponent></parentComponent>"

React Code: –

class MainComponnet extends Component{
 render(){
  let stringComponents = "<parentComponent title='Parent'><childComponent age='23'></childComponent></parentComponent>";
  return(
     {stringComponents}
  )
 }
}

Parent Component JSX : –

class ParentComponent extends Component{
 render(){
  return(
     <div> {this.props.title}</div>
  )
 }
}

Child Component JSX : –

class ChildComponent extends Component{
 render(){
  return(
     <div> {this.props.age}</div>
  )
 }
}

Please help..

Answer

That string has JSX content, you can directly render JSX contents, also the component names must begin with Uppercase charater.

See this answer: React – Adding component after AJAX to view

class MainComponnet extends Component{
 render(){
  let stringComponents = <ParentComponent title='Parent'><ChildComponent age='23'></ChildComponent></ParentComponent>;
  return(
     </div>{stringComponents}</div>
  )
 }
}

In case you cannot use a direct JSX element, you can transform your string to JSX using babel. However its not a good idea. you should rather modify your logic.

You can do it as follows

import babel from 'babel-core';
var Component = eval(babel.transform('<ParentComponent title='Parent'><ChildComponent age='23'></ChildComponent></ParentComponent>).code);
We are here to answer your question about Convert String in React Components - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji