ReactNode vs ReactElement
Nov 24 2024
In React with TypeScript, ReactNode and ReactElement are two important types, but what sets them apart?
ReactNode
ReactNode
is a type that represents any node that could be rendered in React,
including:
- string, number (primitive values)
- JSX.Element
- Arrays of these types
- null or undefined
- boolean (though these are typically ignored)
Here is the example
import React, { ReactNode } from 'react';
// Component accepting ReactNode
interface CardProps {
children: ReactNode;
}
const Card: React.FC<CardProps> = ({ children }) => {
return (
<div className="card">
{children}
</div>
);
};
const App = () => {
const title = "This is a card title";
return (
<div>
<Card>
{title}
</Card>
</div>
);
};
export default App;
ReactElement
On the other hand, ReactElement
is a more specific type that represents a React element. It specifically refers to instances of React components created with:
- JSX
React.createElement
.
Here is the example
import React, { ReactElement } from 'react';
// Component accepting ReactElement
interface ButtonProps {
children: ReactElement;
}
const Button: React.FC<ButtonProps> = ({ children }) => {
return (
<button>{children}</button>
);
};
const App = () => {
const buttonElement: ReactElement = <span>Click Me</span>;
return (
<div>
<Button>{buttonElement}</Button>
</div>
);
};
export default App;
Conclusion
In many cases, you might find yourself using ReactNode for flexibility, but using ReactElement can be beneficial when you want to enforce stricter types for the children of your components.
Thank you for reading.