Home > Net >  Problem when pass data in ReactJS with props and state
Problem when pass data in ReactJS with props and state

Time:03-09

I have the problem when I try to pass the props through the function component .In parent component I have a state of currentRow with return an array with object inside, and I pass it to child component. It return a new object with an array inside it. What can I do to avoid it and receive exact my currentRow array.

there is example of the way I do it Parent component

import React, { useState } from "react";
import ToolBar from "./Toolbar";
function Manage() {
    const [currentRow, setCurrentRow] = useState();
    console.log("from manage", currentRow);
    return (
        <div>
            <ToolBar currentRow={currentRow} />
        </div>
    );
}

export default Manage;

Child Componet

import React from 'react'
function ToolBar(currentRow) {
    console.log("from toolbar", currentRow);
    return(
        <div></div>
    );
}

export default ToolBar

And this is my Log enter image description here

CodePudding user response:

Try accessing it like below:

    import React from 'react'

    function ToolBar({currentRow}) {
        console.log("from toolbar", currentRow);
        return(
           <div></div>
        );
    }

    export default ToolBar

CodePudding user response:

A React component's props is always an object. The reason for this is that otherwise it would be impossible to access the properties of a component which received multiple props.

example:

<SomeComponent prop1={prop1} prop2={prop2} />

---

const SomeComponent = (props) => {
  console.log(props.prop1);
  console.log(props.prop2);
}

So in order to resolve your issue, you could destructure the props object in your ToolBar component like this:

const ToolBar = ({ currentRows }) => {
  ...
}

Just keep in mind that a component will always receive its props as an object. There is no way to change that as of right now.

  • Related