0

I am trying to assign a className for each div mapped from an array of characters valid names except for a period. I used if-statements inside the map function to return the desired react object and it is supposed to "ignore" the period and return a continuous numbered className but instead it does ignore the period but numbers the className incorrectly.

Letters.js

import { Fragment } from "react";

const Letters = () => {
  const characters = "STRI.G".split("");

  const stringBuilder = characters.map((character, i) => {
    if (character !== ".") {
      return <div className={`type${i + 1}`}>{character}</div>; // Works
    } else if (i === 5) {
      // If index value reached the value after '.'
      return <div className={`type${i - 1}`}>{character}</div>; // Does not work, className here remains "type6" instead of "type5"
    } else {
      return <div>{character}</div>; // For when character === '.'
    }
  });

  return <Fragment>{stringBuilder}</Fragment>;
};

export default Letters;

1 Answer 1

1
 else if (i === 5) { // && character === ".", or else we wouldn't get here

you'll only ever get to that else if character === ".", and since i === 4 when that is true, this else might as well not be there. You probably want to reverse the order of all of these checks, if (character === ".") {} else if (i === 5) {} else { /* !== "." */ }

Sign up to request clarification or add additional context in comments.

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.