Search code examples
javascriptreactjsreact-props

Props appear like undefined when a children is passing too


I try to pass a children and props to my component, the children pass well, but the props come like undefined, I cannot figure why. When I don't use children that's work fine. A little snippet to understand the problem. the function

import React from "react";

export function PropsChildren({ children }, props) {
  console.log("info props", props.name, props.age);
  return (
    <div>
      <p>Props name is {props.name}</p>
      <p>Props age is {props.age}</p>
    </div>
  );
}

the call

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
//import App from './App';
import reportWebVitals from "./reportWebVitals";
import { PropsChildren } from "./props/props_children";

ReactDOM.render(
  <React.StrictMode>
    <PropsChildren name="Knupel" age={46}>
      {document}
    </PropsChildren>
  </React.StrictMode>,
  document.getElementById("root")
);

console return info props undefined undefined


Solution

  • props is not the second argument. The props and present the the first object and children is also present there.

    export function PropsChildren({ children, ...props }) {
      console.log("info props", props.name, props.age);
      return (
        <div>
          <p>Props name is {props.name}</p>
          <p>Props age is {props.age}</p>
        </div>
      );
    }