Home > database >  How to navigate through a list
How to navigate through a list

Time:12-13

I want to render all the 'name' elements inside 'rotas', but when i try it says map is undefined. Any help is apreciated.

export default function SelecionaRota(props) {
    const data = {
        locais: [
            {
                name: 'Rio de Janeiro',
                rotas: [
                    {
                        name: 'RJ-SP',
                        valor: 1200
                    },
                    {
                        name: 'RJ-BSB',
                        valor: 1400
                    }
                ]
            }
        ]
    }
    const location = useLocation()
    const { estadoOrigem } = location.state
    return (
        <div>
            <h1>{estadoOrigem}</h1>
            { rota.locais.rotas.map(module => (
                <h1>{module.nome}</h1>
            ))}
        </div>
    )
}

CodePudding user response:

Here's an example of a nested map().

Note: Don't forget to add unique keys to each mapped element (and don't use index).

function SelecionaRota({ data }) {
  //const location = useLocation();
  //const { estadoOrigem } = location.state;

  return (
    <div>
      <h1>estadoOrigem</h1>
      {data.locais.map((locais) => (
        <div key={locais.name}>
          <h2>{locais.name}</h2>
          {locais.rotas.map((module) => (
            <h3 key={module.name}>{module.name}</h3>
          ))}
        </div>
      ))}
    </div>
  );
}

const data = {
  locais: [
    { name: 'Rio de Janeiro', rotas: [{ name: 'RJ-SP', valor: 1200, }, { name: 'RJ-BSB', valor: 1400, },], },
    { name: 'City 2', rotas: [{ name: 'C2-BC', valor: 1200, }, { name: 'C2-EFG', valor: 1400, },], },
  ], 
};

ReactDOM.render(<SelecionaRota data={data}/>, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id="root"></div>

CodePudding user response:

The top level variable is called "data" not "rota" and "locais" is an array not an object. To access rotas:

data.locais[0].rotas.map()
data.locais[1].rotas.map()
//etc

You probably want to iterate over losais like to access each item within.

CodePudding user response:

First of all rota.locais.rotas.map is wrong. You need to use data.locais[0].rotas.

Now as data.locais[0].rotas is an array you need to iterate it using for each. So it will be like this:

Array.from(data.locais[0].rotas).forEach(element => {

<h1>{element.name}</h1>

});
  • Related