Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render a string as children in a React component?

Take a simple component:

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

This works:

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

but this doesn't (I removed the <span/>):

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

because React tries to call render on the string:

Uncaught TypeError: inst.render is not a function

On the other hand, this works fine:

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

How do I make <MyComponent/> behave like <p/>?

like image 893
David Tuite Avatar asked May 26 '16 13:05

David Tuite


1 Answers

If you're using React 16.2 or higher, you can do this using React fragments:

const MyComponent = ({children}) => <>{children}</>

If your editor doesn't support fragment syntax, this will also work:

const MyComponent = ({children}) =>
    <React.Fragment>{children}</React.Fragment>

Keep in mind that you're still creating & returning a component (of type MyComponent) as far as React is concerned - it just doesn't create an additional DOM tag. You'll still see a <MyComponent> tag in the React Debug Tools, and MyComponent's return type is still a React element (React.ReactElement).

like image 142
Andrew Faulkner Avatar answered Nov 02 '22 23:11

Andrew Faulkner