Is there any possibility to pass text between react component tags?

Viewed 18426

I was wondering if it is possible in react to pass data between two React component tags

Example:

Component.js

var React = require('react');

export class MyComponent extends React.Component {
    render() {
        return /*some text*/;
    }
}

App.js

/*rendered to page*/
<MyComponent>How do I display this text?</MyComponent>

I know I could just add this.props.text but just curious if that's an option

3 Answers

Similar to Danny Delott's answer, except simpler with a function component and props destructuring.

export default function MyComponent({ children }) {
  return (
    <div>{children}</div>
  );
}

I like @danny-delott's answer, but you can use React Fragments if you don't want an extra nested div:

export class MyComponent extends React.Component {
    render() {
        return <>{this.props.children}</>
    }
}

Alternatively, one might want to set the "display" property to "contents" to prevent the div from affecting the nested text.

export class MyComponent extends React.Component {
    render() {
        return <div style={{display:"contents"}}>{this.props.children}</div>
    }
}
Related