How to fix the ‘Property is missing in type but required in type’ error in ReactJs

‘Property is missing in type but required in type’ occurs when you pass missing props into the component. To solve the problem, set the default values ​​or make it an option.

What causes ‘Property is missing in type but required in type’ in React?

For example, I want to create a Menu that includes a list of foods.

import React from "react";

type MenuProps = {
  title: string;  
  children: React.ReactNode;
};

const App = () => {
  return (
    <div className = "App">
      <Menu>  
        <div>Eggs</div>
      </Menu>
    </div>
  );
};

const Menu = (props: MenuProps) => {
  return (
    <div>
      <div>{props.title}</div>
      {props.children}
    </div>
  );
};

export default App;

type MenuProps: Declare the type of object to use. Here we will display a string menu name and dishes as the ReactNode.

Create a component function named Menu and pass props of type MenuProps

Finally, we will add the Menu component to the App function.

const App = () => {
  return (
    <div className = "App">
      <Menu>  
        <div>Eggs</div>
      </Menu>
    </div>
  );
};

But when we run the application, we get an error like this:

The above result is because we only pass in the children node and do not have the title attribute while ‘title’ is a defined prop.

How to fix this error?

Pass the necessary props

We will pass the props as required:

Add the ‘title’ attribute to the Menu element and assign a value.

const App = () => {
  return (
    <div className = "App">
      <Menu title = "Menu">  
        <div>Eggs</div>
      </Menu>
    </div>
  );
};

Output: We will get a title named Menu

Menu
Eggs

Or, more simply, we can add a question mark to make prop an option:

type MenuProps = {
  title?: string;  
  children: React.ReactNode;
};

const App = () => {
  return (
    <div className = "App">
      <Menu>  
        <div>Eggs</div>
      </Menu>
    </div>
  );
};

At this point, you may not need to add the title attribute. The title can be a string or get undefined.

Output:

Eggs

Assign default value

We will assign value to the prop when creating the Menu component.

const Menu = ({ title = "Menu", children }: MenuProps) => {
  return (
    <div>
      <div>{title}</div>
      {children}
    </div>
  );
};

{ title = "Menu", children }: Use destructuring to assign the variable and use it immediately.

It is better to pass individual props and assign values ​​to them if your code has an undefined variable.

Summary

If you get the error ‘Property is missing in type but required in type’ in ReactJs, check if all necessary props are passed into the component. And implement one of the solutions that we have come up with.

If you have any questions, feel free to leave us a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *