0

I've created a component that uses a css linear-gradient to render a random linear gradient.

When the user presses a button located somewhere else in my component tree (header), I want the gradient to:

  1. Randomly generate a new gradient
  2. Interpolate the new and old values using react spring

What is the best way to do this? I need to call the genColor() function/ force the component to re-render after it has rendered. Can I call an internal function via a prop?

enter image description here

import React from "react"
import styled from "styled-components"
import { animated, useSpring } from "react-spring"

const Gradient = styled(animated.div)`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  padding: 0;
  margin: 0;
`

const Sky = () => {

  const generateColor = () => {
    let deviation = 33

    let r = Math.random() * deviation + (200 - deviation)
    let g = Math.random() * deviation + (119 - deviation)
    let b = Math.random() * deviation + (88 - deviation)

    r = Math.floor(r)
    g = Math.floor(g)
    b = Math.floor(b)

    let genColor = `rgb(${r}, ${g}, ${b})`
    return genColor
  }

  const interpolate = useSpring({
    background: `linear-gradient(180deg, black, #0d0e1c, #60697F, ${generateColor()})`,
    from: {
      background: `linear-gradient(180deg, black, #0d0e1c, #60697F, ${generateColor()})`,
    },
  })

  return <Gradient style={interpolate} />
}

export default Sky
msalla
  • 717
  • 6
  • 23

0 Answers0