0
votes

I am trying to create a component in React. Rather than listing all the lines of JSX I want to render in the return() section, I sometimes have been storing the information in a variable and just calling {variable}. This has worked well for all other instances other than the one I am stuck on now. I have stripped all of the JSX away leaving an empty div as a tester, but I am still getting the same error:

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {message}). If you meant to render a collection of children, use an array instead.

I would really appreciate any help! Thanks in advance

import React from 'react';
import classes from './Inbox.module.css';


const Cancel = (props) =>{
    let message;
    message =(<div></div>);

    return(
        {message}
    );
}

export default Cancel;
2
This isn't your actual code is it? Do you mean to return message not {message} since it's not JSX as you say - azium

2 Answers

1
votes

Your problem is here,

return(
    {message}
);

{message} is an object and you are trying to render object.

You have two ways to handle this,

Use Fragments

return (
  <React.Fragment> {message} </React.Fragment>
)

Or the short syntax is,

return (
  <> {message} </>
)

Or another way is,

return( 
   message      //without curly braces , not good idea because you may have multiple other elements 
)
0
votes

By doing it the way you did it you return an object message, I guess you want to wrap {message} like this <>{message}</> this way you return jsx and interpolate the variable message

Hope this helps.