Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react split string into words and letters, including spaces with the addition of a ref for each letter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   {"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

>Solution :

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

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

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading