Home > Software design >  Error: React is Returning Objects are not valid as a React child
Error: React is Returning Objects are not valid as a React child

Time:04-22

I'm trying to render some child elements using a reusable button component (class component). The button component accepts some props, and it also renders a Link conditionally.

Below is the code:

  render() {
    const {
      className,
      link,
      children,
      style,
      onClick,
      id,
      value,
      tabIndex,
      name
    } = this.props;

    if (link) {
  
      return (
        <Link className={className} onClick={onClick} to={link}>
          {children} 
        </Link>
      );
    }
    return (
      <button
        value={value}
        style={style}
        className={''}
        onClick={onClick}
        id={id}
        tabIndex={tabIndex}
        name={name}
      >
        {children}
      </button>
      
    );
  }
}

export default Button; 

But React keeps returning an error saying :

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

Both the button and link components render any children they contain.

CodePudding user response:

You are passing an object, React can't render that because it's a complex object, basically it doesn't know what to do with that object. You can pass array or string or integer or other primitive types.

I have made an example here.

Uncomment the line that passes object to the Test component and you see a similar error.

CodePudding user response:

you must use your component this way: (asumming is named class Button ...)

<Button>Hello there!</Button>

Where "Hello there!" is the children prop.

  • Related