Search code examples
arraysreactjsmappingreact-props

map() is not rendering html elements


I had spent 4hrs in this issue but can't figure out what's the problem. Through props I had passed an array(props.content) and wanted to render each element with <h4> tag(not specific) but I can't. It works when I try to console.log each elements of array.

import classes from "./Memes.module.css";
const Memes = (props) => {
        
       return (
         <div className={classes.memes__body}>
         {Array.prototype.forEach.call(props.content,items=>{
             console.log(items)
         })}
          </div> 
       );
}


export default Memes;

Output -

When I try to console.log then it works fine

but It didn't work when I run the same to render all items in some html tags.

import classes from "./Memes.module.css";

const Memes = (props) => {
        
       return (
         <div className={classes.memes__body}>
         {Array.prototype.forEach.call(props.content,items=>{
             <h1>{items}</h1>
         })}
          </div> 
       );
}


export default Memes;

OutPut Doesn't work.

Note - Here props.content is an array of strings.

Fetch_memes.js (Parent one)

import { useState } from "react";
import { useEffect } from "react";
import Memes from "./Memes";

const Fetch_memes = () => {

    const [image, setImage] = useState();
    const [text, setText] = useState("");

    useEffect(() => {
        const memes = async () => {
        const response = await  fetch('https://www.reddit.com/r/memes.json');
    
        if (!response.ok) {
          throw new Error("Something went wrong");
        }
    
        const responseData = await response.json();
        const img = responseData.data.children[0].data.thumbnail;
        const memesCollection = [];
        memesCollection.push("If you can Code then this doesn't mean that your are developer");

        for(let i=0 ; i<20 ; i++){
            memesCollection.push(responseData.data.children[i].data.title);
        }
        
        console.log(memesCollection[1]);
        setImage(img);
        setText(memesCollection);
        }
        memes();
      }, []);

  return (
      <Memes src={image} content={text}/>
  );
}

export default Fetch_memes;

Solution

  • You need to use return in your code:

    import classes from "./Memes.module.css";
    
    const Memes = (props) => {
            
        return (
          < >
          {props.content.map((items)=>{
              return <h1>{items}</h1>
          })}
           </> 
        );
    }
    
    
    export default Memes;