skip to Main Content

First off, let me leave the codesandbox for this problem here.

I am mapping through an array of letters.

const letters = ["A", "B", "C", "D", "E", "F"];

The idea is for all of the letters except the last one to have an arrow below it pointing to the next letter. How can I accomplish this?

const App = () => {
  return (
    <Box>
      {letters.map((letter, index) => (
        <Letter key={index} letter={letter} />
      ))}
    </Box>
  );
};
const Letter = ({ letter }) => {
  return (
    <Box
      display="flex"
      flexDirection="column"
      justifyContent="center"
      alignItems="center"
    >
      <Text>{letter}</Text>
      <ArrowDownIcon />
    </Box>
  );
};

Currently, I am getting what’s pictured below. I need to figure out how to remove the last arrow (the one below ‘F’).

enter image description here

I tried applying _last={{ display: "none" }} to the ArrowDownIcon but this just removed all of the arrows.

2

Answers


  1. You could take CSS pseudo class :last-child.

    Login or Signup to reply.
  2. You can send a prop to the Letter component which checks whether each element is the last or not and render the icon conditionally using the same prop.

    import { Box, Text } from '@chakra-ui/react'
    import { ArrowDownIcon } from '@chakra-ui/icons'
    
    const Letter = ({ letter, isLast }) => {
      return (
        <Box
          display="flex"
          flexDirection="column"
          justifyContent="center"
          alignItems="center"
        >
          <Text>{letter}</Text>
          {!isLast && <ArrowDownIcon />}
        </Box>
      )
    }
    
    export const App = () => {
      const letters = ['A', 'B', 'C', 'D', 'E', 'F']
      return (
        <Box mt={10}>
          {letters.map((letter, index) => (
            <Letter
              key={index}
              isLast={index + 1 === letters.length}
              letter={letter}
            />
          ))}
        </Box>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search