Props are not passing from parent to child components in React Functional component

Viewed 46

Hi developers I'm just a beginner in React.js. I tried to print props by passing from parent to child.

This is app.js file

    import React from "react";
    import Hooks from "./components/ReactHooks1";
    import Hooks2 from "./components/ReactHooks2";
    
    const App = () => {
        return (
            <div>
            <h1>
                Welcome to React App
            </h1>
            <Hooks2 title2={"Welcome"}/>
            </div>
    
        )
    }
    
    export default App

This is child component file

import React from 'react';


const Hooks2 = (props) => {
    console.log(props);
}


export default Hooks2;

I just try to print props but it shows an empty object. what am I doing wrong please help me on this

5 Answers

You should return something or null to parent component from child, when you're using it in parent component. This will solve your problem

export const Hooks2 = (props) => {
    console.log(props);
    return <></>;
}

@Rasith

Not sure why would you want to do this, but if you're trying to pass a child component that would print something to the console. In this case you need to destructure the component's props. Here's an article about it from MDN.

This is how I would do it:

const CustomComponent = ({title}) => {
  console.log(title)
}

const App = () => {
  return (
    <>
      <h1>Hello World</h1>
      <CustomComponent title={"Welcome"}/>
    </>
  );
};

For the title to be printed to the console, no need to add a return statement to the child component. Again, not sure why you would do this, but there you go.

Well trying to console.log title certainly would not work because what you are passing is called title2. Also your child component is not returning anything.

First, you have to return anything from your child component( even a fragment )

You can access title2 in the child component with any of these methods:

1- using props object itself

const Hooks2 = (props) => {
    
    console.log(props.title2);
    
    return;
}

2- you can also destructure props in place to access title2 directly

const Hooks2 = ({title2}) => {

    console.log(title2);
    
    return ;
}

Related