Home > Blockchain >  How to fix 'eslint-disable-next-line react/no-unstable-nested-components'
How to fix 'eslint-disable-next-line react/no-unstable-nested-components'

Time:06-12

I have the following code snippet in my react-native typescript project.

import React from 'react';
import { View, Text } from 'react-native';

import DropDownPicker from 'react-native-dropdown-picker';

const Dropdown = () =>{
  <DropDownPicker
    ArrowDownIconComponent={() => ( // this is the section I getting the error message
      <MaterialCommunityIcons
        name="home-outline"
        size={50}
        color={theme.colors.text}
      />
    )}
  />
}

Due to es-lint, it gives the following error message:

Error message:

Declare this component outside parent component "DropDown" or memoize it. If you want to allow component creation in props, set allowAsProps option to true.eslintreact/no-unstable-nested-components

Image of the error: enter image description here

Can I know how to fix the above error, please?

CodePudding user response:

Just declare the component outside of the parent:


const ArrowDownIconComponent = () => (
  <MaterialCommunityIcons
    name="home-outline"
    size={50}
    color={theme.colors.text}
  />
);

const Dropdown = () =>{
  <DropDownPicker
    ArrowDownIconComponent={ArrowDownIconComponent}
  />
}

Or, memoize it if theme is a state variable of Dropdown component:

const Dropdown = () =>{

  const theme = useTheme();

  const ArrowDownIconComponent = useMemo(() => (
    <MaterialCommunityIcons
        name="home-outline"
        size={50}
        color={theme.colors.text}
      />
  ), [theme.colors.text])

  return (
    <DropDownPicker
      ArrowDownIconComponent={ArrowDownIconComponent}
    />
  );
}

Explanation

Before

ArrowDownIconComponent is redeclared and re-rendered whenever the state is changed

After

ArrowDownIconComponent is declared only once (or redeclared only when theme.colors.text is changed), so it will improve some performance.

  • Related