Skip to content

Instantly share code, notes, and snippets.

@yuvalbl
Last active October 22, 2022 08:32
Show Gist options
  • Save yuvalbl/a1b073ab4430117bf9e4bbb9d24bd71e to your computer and use it in GitHub Desktop.
Save yuvalbl/a1b073ab4430117bf9e4bbb9d24bd71e to your computer and use it in GitHub Desktop.
React and the Missing Children
// Button.tsx
interface Props {
onClick: (event: MouseEvent<HTMLButtonElement>) => void;
children: string;
}
export const Button: FC<Props> = ({ onClick, children }) => {
return (
<button onClick={onClick}>
{children}
</button>
);
};
// usage
<Button>Click Me</Button>
// When children type is string - this will result with the following typescript error:
// Type 'Element' is not assignable to type 'string'
<Button>
<div className="style-that-modify-the-button">
Click Me
</div>
</Button>
// ErrorMessage
import React, {FC} from 'react';
const ErrorMessage: FC = () => {
const { uiStore } = useStores();
if(!uiStore.error) {
return null;
}
return <div className="error-message">{uiStore.error}</div>
}
// usage
<ErrorMessage/>
import React, {FC} from 'react';
interface Props {} // no need to define children
const Message: FC<Props> = ({ children }) => (
<div>{children}</div>
);
import React, {FC, ReactNode} from 'react';
interface Props {
children: ReactNode;
}
const Message: FC<Props> = ({ children }) => (
<div>{children}</div>
);
@yuvalbl
Copy link
Author

yuvalbl commented Oct 21, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment