Home > Mobile >  react split string into words and letters, including spaces with the addition of a ref for each lett
react split string into words and letters, including spaces with the addition of a ref for each lett

Time:11-27

I have a string like "Hello world!".

At the finish I want to see like this: H e l l o    w o r l d !

And ref element for every letter 1 2 3 4 5    6 7 8 9 10 11

   {"Hello world!".split(" ").map((word, index) => {
      return (
        <div
          key={index}
          className="
            mr-4
            flex
          ">
          {word.split("").map((letter, i) => {
            return (
              <div
                className="inline-block"
                key={i}
                ref={(el) => {
                  itemsRef.current[i] = el;
                }}>
                {letter}
              </div>
            );
          })}
        </div>            
      );
    })}

Everything is working now, but the ref for letters looks like this: 1 2 3 4 5    1 2 3 4 5 6

CodePudding user response:

Need to calculate the index based on the parent loop index and current word length

itemsRef.current[index * word.length i] = el;

Demo

CodePudding user response:

The issue here is for each word you start calculation of index from the beginning: in your case "Hello world!".split(" ") this gives you 2, and you are starting twice from the beginning: word.split("")

The simplest solution what can I recommend you is to use length of the list as an index for the next element.

itemsRef.current[itemsRef.current.length] = el
  • Related