Paulo Martins
Paulo Martins
TTCTheo's Typesafe Cult
Created by Paulo Martins on 7/7/2024 in #questions
About Theo's take of not destructuring props
I can't remember in what video exactly, but I heard Theo saying something about using component props without destructuring them. I gave it a go but stumbled on some scenarios where I'm really scratching my head to know how to do properly without destructuring. Basically it's a matter of default values and prop forwarding 1. Default Values
export const NewComponent: React.FC<{ testColor: string } & React.ComponentPropsWithoutRef<"input">> = (props) => {
return (
<label>
<p style={{ background: props.testColor }}>Label</p>
<input {...props} />
</label>
);
};
export const NewComponent: React.FC<{ testColor: string } & React.ComponentPropsWithoutRef<"input">> = (props) => {
return (
<label>
<p style={{ background: props.testColor }}>Label</p>
<input {...props} />
</label>
);
};
I know only of "defaultProps", but not only it is deprecated, but also adds another layer of indirection by having to read the code below at another place
NewComponent.defaultProps = {
testColor: "red"
}
NewComponent.defaultProps = {
testColor: "red"
}
2. Prop Forwarding In the example I gave before, there is a problem: even though I only want to use testColor in the p element, when I use ...props in the input element, I'm passing testColor as well, which throws a warning. How it would be with destructured props
export const NewComponent: React.FC<{ testColor: string } & React.ComponentPropsWithoutRef<"input">> = ({
testColor = "red",
...rest
}) => {
return (
<label>
<p style={{ background: testColor }}>Label</p>
<input {...rest} />
</label>
);
};
export const NewComponent: React.FC<{ testColor: string } & React.ComponentPropsWithoutRef<"input">> = ({
testColor = "red",
...rest
}) => {
return (
<label>
<p style={{ background: testColor }}>Label</p>
<input {...rest} />
</label>
);
};
Also, the React documentation itself only states destructuring as the way to pass default values to components: https://react.dev/learn/passing-props-to-a-component#specifying-a-default-value-for-a-prop
10 replies
TTCTheo's Typesafe Cult
Created by Paulo Martins on 3/7/2023 in #questions
WebSocket workflow for serverless with T3 stack
9 replies