Learner
Learner

Reputation: 21405

How to change each word color in react content

I am working on a task where I need to change the color of each word in a sentence or paragraph in react code for every 1 second.

Here is my code:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      colors: ["red", "yellow", "blue", "green", "purple", "pink"]
    };

    this.changeBg = this.changeBg.bind(this);
  }

componentDidMount() {
    setInterval(this.changeBg, 1000);
 }

  changeBg() {
    const { colors } = this.state;
    const color = colors[Math.floor(Math.random() * colors.length)];
    document.body.style.backgroundColor = color;
  }

  render() {
    return (
      <div>
        This is a sample message in react template
      </div>
    );
  }
}

export default App;

This works fine in changing the background of the content. But my task is to change each word color randomly for every 1 second.

Example for text This is a sample message in react template

This should have one color, is should have another color, similarly all words. How can I do this?

Now these colors should change again every 1 second.

Upvotes: 2

Views: 8843

Answers (3)

Paul Asetre
Paul Asetre

Reputation: 81

You can create a custom component for reuse and replace the html elements to your style needs.

Use case:

<ColorPara>Hello world</ColorPara>

Here's an example:

const getRandomColor = () => {
  const colors = ['red', 'orange', 'green', 'blue']
  return colors[Math.floor(Math.random() * colors.length)];
}

const ColorPara = (props) => {

  return (
    <p>
      {props.children.split(' ').map(text => {
        return (
          <p style={{ color: getRandomColor(), display: 'inline', }}>
            {text} &nbsp;
          </p>
        )
      })}
    </p>
  )
}

function App() {
  //For changing on interval
  //-------------------------
  const [count, setCount ] = useState(0)

  setInterval(() => {
    let newCount = count + 1
    setCount(newCount)
  }, 2000);
  //--------------------------


  return (
    <div className="App">
      <ColorPara>This is something</ColorPara>
    </div >
  );
}

enter image description here enter image description here

edit: added image, added description above block of code, added gif, added color change on interval

Upvotes: 2

bwigs
bwigs

Reputation: 96

Split the sentence on word breaks (spaces) and then apply the randomly chosen color as a style for each word.

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      colors: ["red", "yellow", "blue", "green", "purple", "pink"],
      sampleMessage: "This is a sample message in react template",
      refresh: 0
    };
  }

  refresh() {
    let { refresh } = this.state;
    refresh = refresh + 1;
    this.setState({ refresh });
  }

  componentDidMount() {
    setInterval(this.refresh.bind(this), 1000);
  }

  render() {
    const { sampleMessage, colors, refreshRate } = this.state;

    const randomColor = () => {
      return colors[(Math.random() * colors.length) >> 0];
    };

    return (
      <div>
        {sampleMessage.split(" ").map(word => {
          return <span style={{ color: randomColor() }}>{`${word} `}</span>;
        })}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

see it working here https://codesandbox.io/s/random-word-colors-lu5ew

Upvotes: 2

Chris B.
Chris B.

Reputation: 5763

For each word to have a separate color, it would need to be contained in a discrete element that is able to be individually targeted by CSS.

<div>This is a message</div>

Can only have one CSS rule defining the text color,

<span>This</span><span>is</span><span>better</span>

can have one for each element.

I'd recommend storing your text in state, splitting it into words like any other string, and iterating over the resulting array to render separate elements that you can style as you see fit.

Not sure what you mean exactly by "change randomly," but I tried to make the most basic example I could here

Upvotes: 0

Related Questions