banner
寒寒

寒寒

misskey
github

Props in the passing of React functional components

Recently, while using React for development, I discovered a detail that is easily overlooked, so I wanted to share it.

When using function components, we usually define some props, but we need to be careful about potential issues when passing them as arguments.

Example#

Let's take a look at a function component:

const OneSearch = (query, engine) => {
    ...
}

export default OneSearch;

When referencing this component, you might write it like this:

<OneSearch query={oneSearchQuery} engine={engine}></OneSearch>

At first glance, everything seems fine, but if you carefully observe the definition of the function component, you will notice a small detail in the parameter passing: (query, engine)

In reality, what we actually want is this: ({ query, engine })

Why? Because in React, component parameters are passed as a JavaScript object. When defining a function component, we can write the parameters as (props) or any other name, such as (cop). And when referencing the component, JSX will package the passed parameter names and values into a JavaScript object, which is then passed as an argument to the component. props is just a conventional name, and you can use this name to access the passed parameters.

Another way to write it is ({ query, engine }), where the parameters become an object, and JavaScript syntax allows you to directly access the properties of the object using this form.

However, if you use (query, engine) as the syntax, the situation is different. The first parameter, query, actually receives an object packaged by React, which looks like this:

{
    query: ...,
    engine: ...
}

And! Writing it this way won't cause an error because in JavaScript, functions don't throw errors whether you pass enough arguments, not enough, or even too many. (At least in mainstream browser implementations, it's like this)

In other languages, this kind of writing would have caused an error a long time ago. Python would raise a TypeError at runtime, and compiled languages like C/C++ would start complaining before you even run the compiler, because they can't even pass the compilation.

But JavaScript allows this behavior to happen without any warnings! If you pass too many arguments, they will be assigned to the parameters in the order of the arguments (if you don't specify which argument should be assigned to which parameter when calling the function), and the rest will be ignored. If you pass too few, it's the same. What happens if you reference a parameter that hasn't been assigned an argument? Well, the value of that parameter will be undefined. Just undefined, without even a warning.

Summary#

Therefore, when defining React components, it is recommended to use (props) or ({ prop1, prop2 }) to avoid potential issues.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.