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
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.
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.
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.
You can use the <></> Fragments to pass the HTML in the props.
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>
Similar to Danny Delott's answer, except simpler with a function component and props destructuring.
export default function MyComponent({ children }) { return ( <div>{children}</div> ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With