Home > Software engineering >  React js: Passing API data down to child component in props. Can console.log props but can not rende
React js: Passing API data down to child component in props. Can console.log props but can not rende

Time:10-17

I have been trying to get familiar with React. I have two components. The API call is being made on the parent component and I'm trying to pass the data down to the child component.

This is my parent component:


export default function LandingPage(props) {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/posts").then((response) => {
      setPosts(response.data);
    });
  }, []);

  const classes = useStyles();
  const { ...rest } = props;
  return (
    <div>

      <div className={classNames(classes.main, classes.mainRaised)}>
        <div className={classes.container}>

          {/* HERE IS THE CHILD COMPONENT BELOW */}
          <ProductSection posts={posts} /> 

        </div>
      </div>
      <Footer />
    </div>
  );
}

This is my Child component:


export default function ProductSection(props) {
  const classes = useStyles();

  return (
    <div className={classes.section}>
      {/* HERE IS THE CONSOLE LOG */}
      {console.log(props.posts[0])}
      {/* HERE IS THE RENDER  */}
      <Typography>{props.posts[0]}</Typography>
   </div>

  );
}

ProductSection.propTypes = {
  posts: PropTypes.arrayOf(
    PropTypes.shape({
      userId: PropTypes.number,
      id: PropTypes.number,
      title: PropTypes.string,
      body: PropTypes.string,
    })
  ),
};



Thanks in advance, kinda new to this.

CodePudding user response:

I guess probably your data in props.posts[0] is object, so I would try with JSON.stringify(props.posts[0],null,2).

CodePudding user response:

The data is object, it would be more clear if typography component is shared. Although I tried solving it without the Typography and its working after adding conditional for the non existing postData as data will be fetched and will wait for promise to serve. It is working.

App.js -> Parent

ProductSection.js -> Child

Refer this sandbox which will help you with code. See this sandbox to get more clarity:

LINK

  • Related