DEV Community

MinwooKim
MinwooKim

Posted on • Edited on

Question about style prop in react.

Hello, I have a question of how style property works In react.

I found that if I pass an object to style property of any jsx, it's writable prop gets to false. (code below)

I know it's still writable if I pass a 'destructured object' though, I wonder why React works in this way.

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

const style = {
  color: "red"
};

const styles = {
  color: "blue"
};

export default function App() {
  console.log(Object.getOwnPropertyDescriptor(style, "color")); // writable: true
  console.log(Object.getOwnPropertyDescriptor(styles, "color")); // writable: true

  useEffect(() => {
    console.log(Object.getOwnPropertyDescriptor(style, "color")); // writable: false
    console.log(Object.getOwnPropertyDescriptor(styles, "color")); // writable: true
  }, []);

  return (
    <div className="App">
      <div style={style} styles={styles}>
        hello world
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

if you want to try this in sandBox:
https://codesandbox.io/s/modest-galois-pqtdi?file=/src/App.js

Top comments (0)