Gavin
Gavin

Reputation: 115

React js: Passing API data down to child component in props. Can console.log props but can not render the data

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.

Upvotes: 0

Views: 2029

Answers (2)

Siddharth Varangaonkar
Siddharth Varangaonkar

Reputation: 451

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

Upvotes: 1

Stefan
Stefan

Reputation: 1928

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

Upvotes: 1

Related Questions