Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React eslint error:Component definition is missing display name

Using Reac.memo to wrap my functional component, and it can run smoothly, but the eslint always reminded me two errors:

error    Component definition is missing display name  react/display-name

error    'time' is missing in props validation         react/prop-types

Here is my code:

type Data = {
  time: number;
};
const Child: React.FC<Data> = React.memo(({ time }) => {
  console.log('child render...');
  const newTime: string = useMemo(() => {
    return changeTime(time);
  }, [time]);

  return (
    <>
      <p>Time is {newTime}</p>
      {/* <p>Random is: {children}</p> */}
    </>
  );
});

My whole code:

import React, { useState, useMemo } from 'react';

const Father = () => {
  const [time, setTime] = useState(0);
  const [random, setRandom] = useState(0);

  return (
    <>
      <button type="button" onClick={() => setTime(new Date().getTime())}>
        getCurrTime
      </button>
      <button type="button" onClick={() => setRandom(Math.random())}>
        getCurrRandom
      </button>
      <Child time={time} />
    </>
  );
};

function changeTime(time: number): string {
  console.log('changeTime excuted...');
  return new Date(time).toISOString();
}

type Data = {
  time: number;
};
const Child: React.FC<Data> = React.memo(({ time }) => {
  console.log('child render...');
  const newTime: string = useMemo(() => {
    return changeTime(time);
  }, [time]);

  return (
    <>
      <p>Time is {newTime}</p>
      {/* <p>Random is: {children}</p> */}
    </>
  );
});

export default Father;
like image 259
Liam_1998 Avatar asked Dec 22 '22 18:12

Liam_1998


2 Answers

It's because you have eslint config which requries you to add displayName and propTypes

Do something like

const Child: React.FC<Data> = React.memo(({ time }) => {
  console.log('child render...');
  const newTime: string = useMemo(() => {
    return changeTime(time);
  }, [time]);

  return (
    <>
      <p>Time is {newTime}</p>
      {/* <p>Random is: {children}</p> */}
    </>
  );
});

Child.propTypes = {
  time: PropTypes.isRequired
}

Child.displayName = 'Child';
like image 118
Zohaib Ijaz Avatar answered Mar 01 '23 22:03

Zohaib Ijaz


If you are working with React and TypeScript, you can turn off the react/prop-types rule.

This is because TypeScript interfaces/props are good enough to replace React's prop types.

like image 32
wentjun Avatar answered Mar 02 '23 00:03

wentjun