React: Use `cssText` instead of setting css properties individually

Created on 5 Nov 2015  Â·  4Comments  Â·  Source: facebook/react

Based on the discussion in: https://github.com/facebook/react/issues/5030#issuecomment-153803552

Currently, we diff css properties and imperatively set individual properties for each value that differs from the previous render. We've long claimed that "performance" was the reason, but the benchmarks don't seem to support this claim. For instance, consider Ben's perf test (http://jsperf.com/style-vs-csstext-vs-setattribute/8 (from https://github.com/facebook/react/issues/929). Realistically, there are cases where one technique is faster than the other, and vice versa. It's probably a wash.

But using cssText has several advantages over our current approach. Most notably, it solves correctness issues related to the various css shorthand properties (as noted in https://github.com/facebook/react/issues/5030). It also cleanly solves vendor prefixing, and a variety of other edge cases. Plus, as an added bonus, it means that the React core is doing less work and is therefore simpler/cleaner/moreMaintainable.

All 4 comments

My gut feeling is that this is going in the wrong direction and that it makes no sense to serialize CSS just so that it can be reparsed by the browser (just as we're moving from innerHTML to createElement). This will become even more true as CSS values become more structured in the DOM which there are plans for. But if this really seems better then I'm not really opposed. I think at least some people are relying on the fact that we don't reset inline styles that you don't specify in React though… (e.g., for animations).

I found this page since:

It also cleanly solves vendor prefixing, and a variety of other edge cases.

We want to render inline CSS on server-side but the object representation does not solve display: flex issue. Speaking of the wrong direction, I think it's more like we are standing on a complex ecosystem of browser vendors.

By the way it there anything like dangerouslySetStyle in React?

Hey! I need to be able to set inline styles as cssText. In my case, I should calculate linear-gradient using state like:

render() {
  const gradient = `
     background: -moz-linear-gradient(${this.state.gradient});
     background: -webkit-linear-gradient(${this.state.gradient});
     background: linear-gradient(${this.state.gradient});
  `

  return <div style={gradient}></div>
}

At least, are there any workaround?

As noted by @sophiebits we most likely won’t be doing this.

@Ta4i For your use case, I think you can create a DOM element, try to assign different backgrounds to it, and see which one “sticks”. Here is an example of how to do it. This will tell you the right syntax to use. Then you can have a helper function that uses the right syntax based on that feature test.

Was this page helpful?
0 / 5 - 0 ratings