neutrino
neutrino

Reputation: 924

ReactJS - set CSS keyframe with JSON

I have a React class, that is rendering divs that have their values set by a JSON object array:

class Maps extends Component {
  constructor() {
    super();
    const data = df3;
    this.state = data
  }
  renderDiv = () => {
    var df4 = df3["Devotions"];
    return df4.map(v => {
      return Object.keys(v).map((host) => {
        return (
          <div >
          <div className={host}>
            {host}
            <div className='d3' style={{ 
              transform:`scale(${v[host][3]},${v[host][3]})`}} >
              {v[host][3]}
            </div>
            </div>

          </div>
        );
      });
    });
  };

  render() {
    return <div id="animap">{this.renderDiv()}</div>;
  }

}

export default Maps

but i would like to use the data to set a css keyframe ( rather than a inline style), something like:

.d3{
  position: absolute;
  animation: a3;
  animation-duration: 3s;
  animation-iteration-count:infinite ;
  animation-fill-mode: forwards;
  background-color: rgb(143, 0, 145);
  margin: 0px;
  height: 19px;
  width:19px;
}
@keyframes a3 {

  50%{transform:scale({v[host][3]},{v[host][3]}) ;}

}

The hope is that it's scaling will be animated.

As always, any assistance is appreciated!

Upvotes: 2

Views: 659

Answers (1)

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

You can use inline styles or Web Animations API

Inline style

 render() {
    return <div id="animap">
<style>{`
.d3{
  position: absolute;
  animation: a3;
  animation-duration: 3s;
  animation-iteration-count:infinite ;
  animation-fill-mode: forwards;
  background-color: rgb(143, 0, 145);
  margin: 0px;
  height: 19px;
  width:19px;
}

@keyframes a3 {

  50% { 
    transform: scale(${v[host][3]},${v[host][3]});
  }

}
`}</style>
{this.renderDiv()}
</div>;
  }

Web Animations API



render() {
    return <div ref={divRef => {
      if(!divRef || !divRef.current) {
        return;
      }

      const keyframes = new KeyframeEffect(
      divRef.current, 
      [
        {
         transform: `scale(${v[host][3]}, ${v[host][3]})`,
         offset: 0.5
        }
      ], 
      {
        duration: 100,
        fill: 'forwards'
      }
    );  

    const animation = new Animation(keyframes, document.timeline);

}} id="animap">{this.renderDiv()}</div>;
  }

Upvotes: 1

Related Questions