javascriptreactjsstringletter-spacing

How can you skip a string in this code below?


I am trying to make my message red and white respectively. I have been able to successfully make the message red and white, however the problem is that it takes in to account the spaces in the string. I am trying to make it so that only the letters are respectively red and white and not the spaces. Help would be appreciated, Thank You!!

import React, { useState } from 'react';
import Navbar from './Navbar';
import { Box, Grid, Typography } from '@material-ui/core';
import { Random } from 'react-animated-text';
import Styles from './Styles';
import AboutSkills from './AboutSkills';

const About = () => {
const classes = Styles()

const [color /*setColor*/] = useState({
    message: 'My name is Junaid Razaq and I am a Web Developer',
    colors: [
        'red',
        'white'
        // 'white',
        // 'red'
    ]
})

const colorText = ( message, colorr ) => {
    let mesge = []

    for (let i = 0; i < message.length; i++){
    colorr[i] = colorr[i % 2]
    mesge[i] = (
        <Typography variant='h5' style={{ color: colorr[i], display:'inline-block'}}>
            <Random 
                text={message[i]} 
                effect='jump' 
                effectChange={.1}
                effectDuration={1}
            />
        </Typography>
       )}
    return mesge
 }

return (
    <>
        <Navbar/>
        <Box className={classes.aboutBox}>   
                {colorText(color.message, color.colors)}
        </Box>
    </>
)
}

export default About

Solution

  • One simple (that is implemented withing your existing code) would be to have a different variable to track color.

    const colorText = ( message, colorr ) => {
    let mesge = []
    let colorIndex = 0
    for (let i = 0; i < message.length; i++){
    colorr[i] = colorr[colorIndex % 2]
    if (message[i] != ' ') colorIndex++ //dont change color if space
    mesge[i] = (
        <Typography variant='h5' style={{ color: colorr[i], display:'inline-block'}}>
            <Random 
                text={message[i]} 
                effect='jump' 
                effectChange={.1}
                effectDuration={1}
            />
        </Typography>
       )}
    return mesge
    

    }

    I don't know if this gives color to spaces (I guess it does not), but if it does then you can skip the Typography part if current character is ' '.