user11783025
user11783025

Reputation:

How to fill color to Html?

How to fill different random color to all different p tag in Reactjs

function App() {
  return (
    <div>
      <p>Hi</p>
      <p>Hello</p>
      <p>Cool</p>
      <p>Demo</p>
    </div>
  )
}

Upvotes: 1

Views: 195

Answers (2)

reymon359
reymon359

Reputation: 1330

You can try this approach based on this gist. You can see it working here: https://codesandbox.io/s/random-paragraph-colors-npdlp

function App() {
  const randomColor = () => {
    return "#" + Math.floor(Math.random() * 16777215).toString(16);
  };

  return (
    <div>
      <p style={{ backgroundColor: randomColor() }}>Hi</p>
      <p style={{ backgroundColor: randomColor() }}>Hello</p>
      <p style={{ backgroundColor: randomColor() }}>Cool</p>
      <p style={{ backgroundColor: randomColor() }}>Demo</p>
    </div>
  );
};

enter image description here

Similar case here:

How to change each word color in react content

More about styling in react:

https://reactjs.org/docs/faq-styling.html

Upvotes: 1

Ayushi Keshri
Ayushi Keshri

Reputation: 690

  import React, { Component } from 'react'

export default class Try extends Component {

    getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      }
    render() {
        return (
            <div>
              <p style={{backgroundColor:this.getRandomColor()}}>Hi</p>
              <p style={{backgroundColor:this.getRandomColor()}}>Hello</p>
              <p style={{backgroundColor:this.getRandomColor()}}>Cool</p>
              <p style={{backgroundColor:this.getRandomColor()}}>Demo</p>
            </div>
          )
    }
}

Output: enter image description here

Upvotes: 1

Related Questions