Reputation: 187
Is this function correct React Functional Component? Or why should I use props
object?
function StyledLabel(value, cssClass){
return <span className={cssClass}>{value}</span>
}
Only difference I see is in calling this function:
<App>
{StyledLabel(value, cssClass)}
</App>
Upvotes: 2
Views: 1833
Reputation: 281686
function StyledLabel(value, cssClass){
return <span className={cssClass}>{value}</span>
}
being used like
{StyledLabel(value, cssClass)}
isn't a traditional functional component but a function that returns JSX.
If you follow such a syntax, you won't be able to leverage some functionalities of a functional component such as using React.memo
.
Although you can still use hooks within the functional component.
The other drawback of using such a syntax is that you cannot easily add children components to StyledLabel like you do with the following syntax
<StyledLabel>
<SomeChild/>
</StyledLabel>
Although internally React too invokes the function by calling it and JSX render is a just a Syntactic Sugar
that uses React.createElement
to transpile it but it provides you with a way to make the component a part of the Virtual DOM instead of its return value being part of virtual dom
Upvotes: 5
Reputation: 53884
Function Component is a function which returns JSX
element.
That's a Function Component which invoked as a normal function.
But in this case is hasn't invoked with React.createElement
.
Because JSX is syntactic sugar for React.createElement
, you need to invoke the function with JSX syntax like so:
function StyledLabel({ value, cssClass }) {
return <span className={cssClass}>{value}</span>;
}
<App>
<StyledLabel value={value} cssClass={cssClass} />
</App>
Without invoking React.createElement
, React won't be aware of the component (for state updates, diffing algorithm etc.), as it will be just a normal function call.
Yet another major problem is the function arguments:
// Not function StyledLabel(value, cssClass)
function StyledLabel(props)
React.createElement
accepts a single argument which is the component's props.
React.createElement(
type,
[props],
[...children]
)
Upvotes: 5