Search code examples
javascriptreactjstypescriptchakra-ui

TypeError: props.map is not a function


BottomMissionText.tsx

import React from "react";
import { Center, Text } from "@chakra-ui/react";
import IMissionText from "../../interfaces/AboutPage/IMissionText";

//Simple bottom mission text component
export default function BottomMissionText(props: Array<IMissionText>) {
    return (
        <Center pt={5}>
            {props.map((i) => (
                <Text>{i.title}</Text>
            ))}
        </Center>
    );
}

IMissionText.ts

export default interface IMissionText {
    title: string;
    text: string;
}

MissionBox.tsx(snippet)

<Box>
    {isT !== false ? (
       <BottomMissionText {...traditionalStatement} />
    ) : null}
    {isL !== false ? (
    <BottomMissionText {...traditionalStatement} />
    ) : null}
</Box>

I've been trying this for almost two hours now, and I keep getting this error (title).


Solution

  • In order to pass multiple objects, inside your MissionBox.tsx you should define traditionalStatement as an array of objects

    const traditionalStatement: IMissionText[] = [
        {
            title: "your title1 string",
            text: "your text1 string",
        },
        {
            title: "your title2 string",
            text: "your text2 string",
        }
    ]
    
    // ... rest of your component's code
    
    <Box>
        {isT !== false ? (
           <BottomMissionText traditionalStatement=traditionalStatement />
        ) : null}
        {isL !== false ? (
        <BottomMissionText traditionalStatement=traditionalStatement />
        ) : null}
    </Box>
    

    In the functional component, you need to define the schema of props. I have named it IBottomMissionTextProps. And then de-structure the traditionalStatement from props in the functional component like the below code. Or directly use props.traditionalStatement in map.

    import React from "react";
    import { Center, Text } from "@chakra-ui/react";
    import IMissionText from "../../interfaces/AboutPage/IMissionText";
    
    interface IBottomMissionTextProps {
        traditionalStatement: IMissionText[];
    }
    
    //Simple bottom mission text component
    export default function BottomMissionText(props: IBottomMissionTextProps) {
        const { traditionalStatement } = props; // destructuring
        // alternatively, you can use 
        // const traditionalStatement = props.traditionalStatement;
    
        return (
            <Center pt={5}>
                {traditionalStatement.map((i) => (
                    <Text>{i.title}</Text>
                ))}
            </Center>
        );
    }