3

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..

Kracki
  • 63
  • 1
  • 12

2 Answers2

1

Thanks alot for every one for helping me. Library 'react-jsx-parser' solved my problem .

Kracki
  • 63
  • 1
  • 12
0

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);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thanks for Reply @Shubham but if you will notice my string is surronded by double quotes and yours not. Its data type is string hence while render its not processing react component. – Kracki Jun 16 '17 at 14:37
  • Exactly my point, you dont need to surround your string within double quotes, directly assign the JSX content to the variable – Shubham Khatri Jun 16 '17 at 14:38
  • I don't have any other options, this is what am getting in json from backend. If I can remove that quotes on UI or any other way to load component from String would be helpful. – Kracki Jun 16 '17 at 14:47
  • Added that part in the answer – Shubham Khatri Jun 16 '17 at 14:55