0

I am using react functional component. When I run react it outputs this error "TypeError: Cannot read property 'map' of undefined"

Sample Data

const tabData = [{
    key: 0,
    label: 'Theory',
    color: 'primary',
    theory: [{
        key: 0,
        title: 'Analyze one dimensional and two dime',
        content: [
                'Kinematics',
                'Rectilinear motion under constant acceleration',
                'Equations of motion',
        ],
    }]
}];

My function

{tabData.map((data) => {
    return (
        <TabPanel value={value} index={data.key}>
           <ul index={data.key}>
              {data.theory.map((tit) => {
                 return (<li key={tit.key}>{tit.title}</li>);
              })}
          </ul>
        </TabPanel>
    );

})}

2 Answers 2

1

Use optional chaining for this case. It's much shorter and cleaner.

{tabData?.map((data) => {
    return (
      <TabPanel value={value} index={data.key}>
        <ul index={data.key}>
        {data.theory.map((tit) => {
          return (<li key={tit.key}>{tit.title}</li>);
        })}
        </ul>
     </TabPanel>
    );
Sign up to request clarification or add additional context in comments.

Comments

0

You can write something like this

{tabData && tabData.length > 0 && tabData.map((data) => {
    return (
      <TabPanel value={value} index={data.key}>
        <ul index={data.key}>
        {data && data.theory && data.theory.length > 0 && data.theory.map((tit) => {
          return (<li key={tit.key}>{tit.title}</li>);
        })}
        </ul>
     </TabPanel>
    );
})}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.