Home > database >  React: TypeError: items.map is not a function. Even though my state is an array
React: TypeError: items.map is not a function. Even though my state is an array

Time:10-20

Issue: within my child component: TypeError: items.map is not a function

I don't understand why not, I saw that others had this issue when they were mapping through something that wasn't an array. However mine clearly is. As seen on the fourth line in the parent component.


Parent comp:

import React, {useState} from 'react';
import ListItem from '../components/listItem';

const Pagethree = () => {
const[items,setItem] = useState([]);
return(
    <div>
        <CreateItem items={items} setItem={setItem}/>
        <ListItem items={items}/>
    </div>
)
};

export default Pagethree;

Child comp 1:

import React, {useState} from "react";

const ListItem = (props) =>{
const {items} = props;
return(
    <div>
        <h1>list item comp</h1>
        <ul>
            {
            items.map((item, i) =>
                <div class="flex">
                    <input type="checkbox" />
                    {item}
                    <button>delete</button>
                </div>
            )
            }
        </ul>
    </div>
)
};

export default ListItem;

child component 2:

import React from "react";

const CreateItem = (props) =>{
const {items, setItem} = props;
const addItem = (e) =>{
    e.preventDefault();
    setItem([...items, items]);
    setItem("");
    console.log(items);
}
return(
    <div>
        <h1>create item comp</h1>
        <form onsubmit={addItem}>
            <input type="text" value={items} onChange={e => setItem(e.target.value)}/>
            <button type="submit">add item</button>
        </form>
    </div>
)
};

export default CreateItem;

CodePudding user response:

When you call setItem on input change (in CreateItem) you’re setting the state on the parent component to a single (non-array) value. The subsequent render throws because items is no longer an array.

CodePudding user response:

It is props problem, map syntax also problem

import React, {useState} from "react";
const ListItem = ({items}) =>{

return(
    <div>
        <h1>list item comp</h1>
        <ul>
            {
            items.map((item, i) =>(
                <div class="flex">
                    <input type="checkbox" />
                    {item}
                    <button>delete</button>
                </div>)
            )
            }
        </ul>
    </div>
)
}

export default ListItem;
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related