Search code examples
reactjsreact-propsuse-effectuse-statereact-functional-component

How to pass props to child React component?


How can i pass props to React Child Component ? I got error:

TypeError: Cannot read property 'user_id' of null

child
D:/T97/React-Test/test/src/child.js:6
  3 | const child = (props) => {
  4 |   const {user} = props;
  5 |   return (
> 6 |     <div className="child">
  7 |       {user.user_id}
  8 |     </div>
  9 |   );
View compiled

When i replace user.user_id in child.js by JSON.stringify(user), i got:

{"user_id":1,"password":"null","user_name":"User1","email":"user@gmail.com","avatar_url":"https://picsum.photos/300/300"}

API: ("http://localhost:5000/user/1")

{"user_id":1,"password":"null","user_name":"User1","email":"user@gmail.com","avatar_url":"https://picsum.photos/300/300"}

App.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Child from './child';
function App() {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios.get(
        'http://localhost:5000/user/1',
      );
      setUser(result.data);
    };
 
    fetchData();
  }, []);
  
  return (
    <div className="App">
      <Child user={user}/>
    </div>
  );
}
 
export default App;

child.js

import React from 'react';

const child = (props) => {
  const {user} = props;
  return (
    <div className="child">
      {user.user_id}
    </div>
  );
};

export default child;

Solution

  • For the first rendering the user is not yet available (it's null initially), after the axios request/response is done the user will be available and you could use in your components, but you have to add a conditional rendering when the user is null :

       <div className="child">
          {user && user.user_id}
        </div>