Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs - TypeError: Cannot assign to read only property 'transform' of object '#<Object>'

I was planning to change the inline css by hovering the element. But react freaked out cuz all the properties of the 'style' object in this class are somehow all readonly.

But it is fine to modify it in 'render' method. I searched the error message, many people get this error message by modifying the props object.But this one is not even in the props object. Any ideas?

Here's my code:

import React, { Component } from 'react';

export default class Game extends Component {
   state = {

   }

   style = {
      height: '200px',
      backgroundImage: 'url()',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      transform: 'scale(1)'
   }

   onHover() {
      this.style.transform = 'scale(1.2)';
   }

   render() {
      const { game, onClick } = this.props;
      const { img, name } = game;
      this.style.backgroundImage = `url(${img})`;
      this.style.transform = 'scale(1)';
      return (
         <div className="m-2"
            style={this.style}
            onClick={() => { onClick(this.props.game) }}
            onMouseEnter={() => this.onHover()}
         >{name}</div>
      );
   }
}

Can't attach images yet, so here's the link for the error message.

Error message screenshot

like image 568
Hao Wu Avatar asked Sep 03 '18 04:09

Hao Wu


1 Answers

The only way to update the property in react is to update the state with setState. Alternatively, you should place them inside the render hook itself or where you require them:

render() {
  const { game, onClick } = this.props;
  const { img, name } = game;
  const style = {
      height: '200px',
      backgroundImage: 'url()',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      transform: 'scale(1)'
   }
  // now, you can modify
  style.backgroundImage = `url(${img})`;
  style.transform = 'scale(1)';

Or, even you may place them outside the class: (This would be preferred method in your case because, you're updating the properties in desired methods)

const style = {
   height: '200px',
   backgroundImage: 'url()',
   backgroundSize: 'cover',
   backgroundRepeat: 'no-repeat',
   backgroundPosition: 'center',
   transform: 'scale(1)'
}
export default class Game extends Component {
  render() {
    // modifying style
    style.backgroundImage = `url(${img})`;
    style.transform = 'scale(1)';
like image 77
Bhojendra Rauniyar Avatar answered Nov 02 '22 09:11

Bhojendra Rauniyar