Using a React component to display an array of numbers with a unique background color

My task is to create a React component that displays an array of numbers from 1 to 100 with different background colors assigned to even, odd, and prime numbers.

Currently, I have the Random Component rendering inside the App component.

I am struggling with generating the appropriate colors for each type of number.

Below is my progress so far:

App Component

import React from 'react'
import Numbers from './Numbers'
import './Style.css'

export default function App() {
    // const numbers = [1]

const numbers = [];
for(let i=0; i<=31; i++){
    numbers.push(i);
    if(i % 2 === 0){
        // numbers.style.backgroundColor = 'green' ; 
    }
   }
    return (
      <div className='container'>
        <div className="child">
          <h1>Numbers List</h1>
          <ul>
            <Numbers className="block" numbers={numbers} />
            {/* <Numbers/> */}
          </ul>
        </div>
        
      </div>
    )
}

Number Component

import React from 'react'

export default function Numbers({ numbers }) {
  const list = numbers.map((number) => 
  <div key={number} className="numbers"><li  className="list">{number}</li></div>
  )
  return list
}

Style sheet

body{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
} 
.container{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
} 
.numbers{
  background-color: pink;
  width: 100px;
  height: 100px;
  border-right: 1px solid gray;
  border-bottom: 1px solid aliceblue;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}
li{
  text-align: center;
  padding-top: 15px;
  font-size: 1.2rem;
  padding-left: 15px;
}

Answer №1

If you're looking to achieve a similar result, consider the following implementation:

import React from 'react'

export default function Numbers({ numbers }) {
  const isPrime = num => {
    for(let i = 2; i < num; i++) {
      if(num % i === 0) return false;
    }
    return num > 1;
  }

  const isOdd = (num)=> { 
    return num % 2;
  } 

  const getBackGroundColor = (num)=>{
    let color = 'red';
    if(isOdd (num)) 
      color ='red'; //even
    else 
      color ='green'; //odd
    if(isPrime(num)) 
      color = 'orange'; //prime 
    return color ;
  }

  const list = numbers.map((number) => (
    <div key={number} style={{backgroundColor: getBackGroundColor(number) }} className="numbers"><li  className="list">{number}</li></div>
  ));

  return list;
}

Answer №2

To create a unique and dynamic design, the following CSS code is implemented:

li:nth-child(2),
li:nth-child(odd) {
  background: pink;
}

li:first-child,
li:nth-child(3n+6),
li:nth-child(5n+10),
li:nth-child(7n+14)
{
  background: grey
}

li:nth-child(2n+4) {
  background: silver
}

Answer №3

This method is effective for me as it utilizes the random color generator function to fetch a color from an array.

const generateRandomColor = () => {
    const colors = ["#452132", "#689712", "#AD6701", "#FFCD34"];
    const randomColor = colors[Math.floor(Math.random() * colors.length + 0)];
    return randomColor;
  }
generateRandomColor();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today. The issue lies with my interface: interface ICustomer { id: number, first_name: string } I ...

Show the initial three divs first before implementing a toggle for the rest

My dashboard consists of multiple panels, each containing various items. Some panels have a large number of items. I am looking to display only the first three items in each panel and provide a toggle option to show/hide the rest. <div class="dashboa ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...

The authentication middleware is being executed for all routes within my app.js file, despite my intention to only apply it to a single route

I have developed a requireAuth middleware and integrated it into my app.js. In app.js, I have also imported all the routes from the routes folder. Each route.js file contains multiple chained routes. When I include the auth middleware in one of those files ...

Guide to using react-router for redirection and displaying messages

Is there a way in React to redirect after a successful login with a success message displayed on another component? I previously used flash messages, but they didn't integrate well with react-router and caused full page refreshes. Now that I am using ...

Hold off on advancing until the particular text is found in the DOM element

One of the challenges I'm facing is creating a function that waits for specific text to change before returning a value: function getElementText() { while(isLoading()) { } return $('#element').text(); } function isLoading() { ...

What is the best way to ensure a footer works on both a PWA and browser on a page?

Developing a Progressive Web App (PWA) has presented numerous challenges, particularly in ensuring responsiveness. In an attempt to create a footer for the page, I defined the following classes: #root { height:100vh; } .provider-container { padding ...

javascript with a focus on objects

Having trouble with the scene.add(Obj); line for my object player1. I keep getting an error saying that Obj does not exist: function Player(x, y, z) { this.Speed = 0; this.AngleAcc = 0; this.Angle = 0; this.X=x; this.Y=y; this.Z=z; this.MaxSpeed = ...

Where should image manipulation be done - on the server or the client side?

Currently, I am working on a Django-based web application that involves online image manipulation. The goal is to give users the ability to upload their images, apply various manipulations like cropping, filters, and re-ordering, and then send the modified ...

Having trouble invoking an express route on mobile devices using the .click method

I'm experiencing a strange issue where my code works perfectly in Chrome browser but fails to function on my phone. Here's the snippet of code causing the problem: $('#plusSign').on('click', function() { var myLin ...

Attempting to crack the code within body-parser and Node.js

I am just getting started with Node.js & Express and trying to follow a tutorial at https://github.com/jw84/messenger-bot-tutorial. I have a good understanding of most parts, but I'm confused about the use of "entry" and "messaging" in this code snipp ...

Converting promises in JavaScript

Understanding the concept of promises has been a challenge for me. While I have come across some examples that shed light on it, applying those concepts practically is where I face difficulties. Here's an example illustrating my dilemma: (For this cod ...

The Subscribe Box's style seems to be overridden somewhere, but I can't figure out where

I am currently working on customizing the appearance of my subscription box located at to resemble the one shown on . The issue I'm facing is that the subscribe box appears much smaller than desired. It seems there may be a conflicting style that nee ...

Retry request with an AngularJS interceptor

Currently, I am in the process of developing an Angular application and encountering some challenges while implementing a retry mechanism for the latest request within an HTTP interceptor. The interceptor is primarily used for authentication validation on ...

Tips for rotating a canvas object without changing its position

I am currently in the process of developing a JavaScript game centered around a character positioned on top of the world. Although the earth element is already part of the game, I am encountering an issue with its rotation causing it to shift position as w ...

Struggles with my initial attempts at Redux Toolkit practice

I am relatively new to coding and I have been trying my hand at learning redux toolkit. However, I am facing some challenges when it comes to fetching data from PokeAPI. My aim was to retrieve data from PokeAPI, but every query I attempt gets rejected and ...

Encountering a failure when trying to run npm in a React project

I've removed the .lock file and node_modules, then reinstalled, but it's still not working. Can someone assist me with fixing this? npm ERR! gyp ERR! node -v v16.13.0 npm ERR! gyp ERR! node-gyp -v v8.2.0 npm ERR! gyp ERR! not ok npm ERR! node-pr ...

Infinite loop triggered by jQuery dropdown menu on page resize was causing an issue

I have been working on developing a navigation menu for a website that displays as a horizontal bar on larger screens, but transforms into a jQuery dropdown menu when the window width is less than 980px. During initial page load with a window width below ...

Retrieve information using Observables just once in Angular 2

One of my Angular 2 components relies on a service that fetches customer data from a Web API and returns an Observable: getCustomers() { return this.http .get(this.baseURI + this.url) .map((r: Response) => { let a = r.jso ...

Usage of recursive function with process.stdin.on in Node.js leads to unintended repetitive actions

As a newcomer to Node.js, I find myself in need of assistance with the following function that I've created: The function called 'loopDialog' requires an object and a starting index as parameters. It initiates a dialog allowing users to: ...