I'm new to React, and I just can't figure this out...
I'm trying to pass my state to a prop in the parent component, and then render that state in a child component. Like so:
class App extends Component {
constructor(props) {
super(props);
this.state = {
text: 'hello'
}
}
render() {
return (
<div className="App">
<MessageList textProp={this.state.text}/>
</div>
);
}
}
const MessageList = textProp => {
return (
<div className='MessageList'>
{textProp}
</div>
)
}
React won't render properly, claiming it is an object that is trying to be rendered.
I can access the property by using {textProp.textProp}
, why is it rendering an object which contains a property of the same name?
I'm sure this is very simple but I could do with an explanation!
Thanks in advance.
Components' props are an object, just as their state is an object. Therefore you want something more like:
const MessageList = props => {
return (
<div className='MessageList'>
{props.textProp}
</div>
)
}
or, using destructuring:
const MessageList = ({ textProp }) => {
return (
<div className='MessageList'>
{textProp}
</div>
)
}
When you declare stateless component you need to specify the arguments you want it to receive it can be (props)
or ({ specific })
in your case:
const MessageList = ({ textProp }) => (
<div className='MessageList'>
{textProp}
</div>
);
Note how i do => ()
that will return the markup, you don't have do to { return () }
just a tip to run things better :)
The textProp
in MessageList
is a collection of props
form the parent. In your case the collection will have only textProp.
To make this work you need to do the following.
const MessageList = ( {textProp} ) => {
return (
<div className='MessageList'>
{textProp}
</div>
)
}
or
const MessageList = (textProp) => {
return (
<div className='MessageList'>
{textProp.textProp}
</div>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.