Dan Cantir
Dan Cantir

Reputation: 2955

ESLint rule forbidding Object Literals in JSX

This article says: Beware of Object Literals in JSX

Once your components become more “pure”, you start detecting bad patterns that lead to useless rerenders. The most common is the usage of object literals in JSX, which I like to call “The infamous {{”. Let me give you an example:

import React from 'react'; 
import MyTableComponent from './MyTableComponent';

const Datagrid = (props) => (
     <MyTableComponent style={{ marginTop: 10 }}>
         ...
     </MyTableComponent> 
 )

The style prop of the component gets a new value every time the component is rendered. So even if is pure, it will be rendered every time is rendered. In fact, each time you pass an object literal as prop to a child component, you break purity. The solution is simple:

import React from 'react'; 
import MyTableComponent from  './MyTableComponent';

const tableStyle = { marginTop: 10 }; 

const Datagrid = (props) => (
     <MyTableComponent style={tableStyle}>
         ...
     </MyTableComponent> 
) 

This looks very basic, but I’ve seen this mistake so many times that I’ve > developed a sense for detecting the infamous {{ in JSX. I routinely replace it with constants.

So my question is, is there any rule preventing using object literals in jsx?

I'm trying to find one, but no results yet.

Upvotes: 2

Views: 3600

Answers (1)

Dawid Karabin
Dawid Karabin

Reputation: 5293

Edit

I've found this plugin https://github.com/cvazac/eslint-plugin-react-perf in one comment below this article: React.js pure render performance anti-pattern.

This plugin offers rules below:

  • react-perf/jsx-no-new-object-as-prop: Prevent {...} as JSX prop value
  • react-perf/jsx-no-new-array-as-prop: Prevent [...] as JSX prop value
  • react-perf/jsx-no-new-function-as-prop: Prevent function as JSX prop value
  • react-perf/jsx-no-jsx-as-prop: Prevent JSX as JSX prop value

I think that this is exactly what you need.


Based on my quick look at https://github.com/yannickcr/eslint-plugin-react, I could not find any rule related to this issue. I think it's a good time for a pull request!

Right now you can use jsx-no-bind rule which checks for extra functions created on each render so thanks to this rule you can also prevent extra renders in your components.

https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md

Upvotes: 7

Related Questions