Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 346
rileyjsumner Avatar asked Aug 02 '17 23:08

rileyjsumner


People also ask

How do you pass values between components in React?

Passing data from a Parent component to Child is the easiest way of data passing among the above three topics. We can simply use 'props' in ReactJs to make the child inherit properties from its parent component. and define the real value of 'value' inside the Parent class.

Can you pass state between components React?

Props: It allows you to pass data from a parent component to a child component. State: While props allow you to pass data from a parent component to a child component, the state is used to change the component, well, state from within.

How many ways we can communicate between components in React?

I saw that the question is already answered, but if you'd like to learn more details, there are a total of 3 cases of communication between components: Case 1: Parent to Child communication. Case 2: Child to Parent communication. Case 3: Not-related components (any component to any component) communication.

Can we pass HTML as props in React?

You can use the <></> Fragments to pass the HTML in the props.


2 Answers

You can use this.props.children:

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

And then write it as a JSX element:

<MyComponent>How do I display this text?</MyComponent> 
like image 135
Danny Delott Avatar answered Sep 25 '22 23:09

Danny Delott


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

export default function MyComponent({ children }) {   return (     <div>{children}</div>   ); } 
like image 22
datchung Avatar answered Sep 25 '22 23:09

datchung