Paulos3000 Paulos3000 - 2 months ago 8
React JSX Question

React Prop rendering as object - don't understand why

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:

Parent Component



class App extends Component {
constructor(props) {
super(props);
this.state = {
text: 'hello'
}
}
render() {
return (
<div className="App">
<MessageList textProp={this.state.text}/>
</div>
);
}
}


Child Component



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.

Answer

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>
   )
}