Home > front end >  reusing array.map() in React.js
reusing array.map() in React.js

Time:09-26

I can't find an answer in "many similar questions", sorry I'm new to react. I have the following code inside return of my sfc that works/renders fine:

{data && allToDos && completed === 'all' && data.map(data => {
        key  ;
        return (
            <div key={key}>
                <h2>{data.title}</h2>
                <p className="apart">
                    Nr: {data.id} <span>Status: {!data.completed && <span>Not </span>}completed</span>
                </p>
                <h3>User: {data.userId}</h3>
                <br/><hr/><br/>
            </div>
        );
    });}

Now, I have 3 different options for completed and in each case i want to render different set of data, so i have isolated the data.map(data => {/*code*/}) into a separate function inside the same component,like that:

const dataMap = () => {
    data.map(data => {
        key  ;
        return (
            <div key={key}>
                <h2>{data.title}</h2>
                <p className="apart">
                    Nr: {data.id} <span>Status: {!data.completed && <span>Not </span>}completed</span>
                </p>
                <h3>User: {data.userId}</h3>
                <br/><hr/><br/>
            </div>
        );
    });
}

and then i passed that function inside return like that:

{data && allToDos && completed === 'all' && dataMap()}

and nothing is rendered, but no error messages either.

CodePudding user response:

You're not returning from dataMap() function it returns undefined .

try this

const dataMap = () => {
return data.map(data => {
    key  ;
    return (
        <div key={key}>
            <h2>{data.title}</h2>
            <p className="apart">
                Nr: {data.id} <span>Status: {!data.completed && <span>Not </span>}completed</span>
            </p>
            <h3>User: {data.userId}</h3>
            <br/><hr/><br/>
        </div>
    );
});

}

  • Related