简体   繁体   中英

"Objects are not valid as a React child" and linters

I have an issue about a simple component and I don't know why. Here is my error and my code :

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

import React from 'react';
import './Label.css';

export default function Label(Childn, Cfor) {
  return (
    <label className="label mr-10" htmlFor={Cfor}>
      {Childn}
    </label>
  );
}

I used some linters and I'm trying to follow the style guide of airbnb. But in another branch of my project which hasn't the linters, this code works. So I guess it's a problem of compatibility with the linters. Here is my devDependencies and my .eslintrc.json

  "devDependencies": {
    "eslint": "^7.13.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jest": "^24.1.0",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.21.5",
    "eslint-plugin-react-hooks": "^4.2.0",
    "stylelint": "^13.7.2",
    "stylelint-config-standard": "^20.0.0"
  }
{
    "env": {
        "browser": true,
        "es2021": true,
        "jest": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "airbnb",
        "airbnb/hooks"
    ],
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
    }
}

How can I fix that? Some has an idea?

Thanks by advance!

Functional components' first parameter should be props which is an object. then you access children or other props from it

export default function Label(props) {
  const { children, Cfor } = props;
  return (
    <label className="label mr-10" htmlFor={Cfor}>
      {children}
    </label>
  );
}

In addition, you cannot render an object directly. Instead you can render JSON.stringify(object)

import React from 'react';
import './Label.css';

export default function Label({Childn, Cfor}) { // <--- attention
  return (
    <label className="label mr-10" htmlFor={Cfor}>
      {Childn}
    </label>
  );
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM