How to edit a string as children in a React component?

Take a simple component:

function MyComponent({ children }) { return children; } 

It works:

 ReactDOM.render(<MyComponent><span>Hello</span></MyComponent>, document.getElementById('stage')); 

but this is not the case (I deleted <span/> ):

 ReactDOM.render(<MyComponent>Hello</MyComponent>, document.getElementById('stage')); 

because React is trying to call render on a line:

 Uncaught TypeError: inst.render is not a function 

On the other hand, this works great:

 ReactDOM.render(<p>Hello</p>, document.getElementById('stage')); 

How to make <MyComponent/> behave like <p/> ?

+5
source share
4 answers

Well, the difference <p> is an html element and MyComponent is a React component.

React components need to visualize / return either one component or one html element.

'Hello' not.

+1
source

Currently, in the render component, you can only return node; if you have, say, a list of divs to return, you must wrap your components within a div, span, or any other component.

a source

And what you return is not the root of the node. You are returning a reaction component that returns a string where it should return an HTML element.

You can pass your string already wrapped in an HTML element (for example, you already did this in your example), or you can wrap your string in an HTML element inside your "MyComponent", like this

 function MyComponent({ children }) { return <span>{ children }</span>; } 
+1
source

You need at least one top-level HTML element. Your component cannot just output a string; this is not how React works.

The simplest solution is to simply make your MyComponent complete its output in a range or div.

 function MyComponent({ children }) { return <span>{ children }</span>; } 
0
source

React can display either React components (classes) or HTML tags (strings). Any HTML tag has a conditional string value, where the component is capitalized. Each React component must display exactly one tag (or zero). To answer your question: you cannot.

In the above example, you visualize what is specified with the children attribute, where the tag inside or a string that is not valid will be displayed.

0
source

All Articles