score:125
Here's a similar question with an answer: React with TypeScript - define defaultProps in stateless function
import React, { Component } from 'react';
import { Text } from 'react-native';
interface TestProps {
title?: string,
name?: string
}
const defaultProps: TestProps = {
title: 'Mr',
name: 'McGee'
}
const Test: React.SFC<TestProps> = (props) => (
<Text>
{props.title} {props.name}
</Text>
);
Test.defaultProps = defaultProps;
export default Test;
score:-5
To me, this doesn't look like a typescript issue.
DISCLAIMER: I have only tried this with typescript.
However, the problem is that props always exists (even as an empty object when nothing is passed in). There are 2 workaround for this, though.
The first, unfortunately, kills the super clean curly-brace-less syntax you have, but let's you keep defaultProps
around.
interface TestProps {
title?: string;
name?: string;
}
const defaultProps: TestProps = {
title: 'Mr',
name: 'McGee'
}
const Test = (passedIn: TestProps) => {
const props = Object.assign({}, defaultProps, passedIn);
return (
<p>
{props.title} {props.name}
</p>
);
}
another alternative that might get a little hairy if you have a TON of props, but that lets you keep your original syntax is something like this:
const Test = (props: TestProps) => (
<Text>
{props.title || 'Mr'} {props.name || 'McGee'}
</Text>
);
Hope this helps!
score:0
I might be wrong, but passing the a default prop value on the function as the second voted reply says could lead to subtle bugs or over executed useEffects (I don't have enough rep to reply there, so here's a reproducible codesanbox)
Even if it's a really contrived example, and probably in most of the cases just bad component design, I have seen this more than once, even breaking full pages.
score:1
Adding my solution to the pot, I think it adds an additional level of readability and elegance onto the existing solutions.
Let's say you have a component MyComponent
with a mix of required and optional props. We can separate these required and optional props into two interfaces, combining them for the full prop interface of the component, but only using the optional one to set the default props:
import * as React from "react";
// Required props
interface IMyComponentRequiredProps {
title: string;
}
// Optional props
interface IMyComponentOptionalProps {
color: string;
fontSize: number;
}
// Combine required and optional props to build the full prop interface
interface IMyComponentProps
extends IMyComponentRequiredProps,
IMyComponentOptionalProps {}
// Use the optional prop interface to define the default props
const defaultProps: IMyComponentOptionalProps = {
color: "red",
fontSize: 40,
};
// Use the full props within the actual component
const MyComponent = (props: IMyComponentProps) => {
const { title, color, fontSize } = props;
return <h1 style={{ color, fontSize }}>{title}</h1>;
};
// Be sure to set the default props
MyComponent.defaultProps = defaultProps;
export default MyComponent;
score:16
Here's how I like to do it:
type TestProps = { foo: Foo } & DefaultProps
type DefaultProps = Partial<typeof defaultProps>
const defaultProps = {
title: 'Mr',
name: 'McGee'
}
const Test = (props: Props) => {
props = {...defaultProps, ...props}
return (
<Text>
{props.title} {props.name}
</Text>
)
}
export default Test
score:84
I've found the easiest method is to use optional arguments. Note that defaultProps will eventually be deprecated on functional components.
Example:
interface TestProps {
title?: string;
name?: string;
}
const Test = ({title = 'Mr', name = 'McGee'}: TestProps) => {
return (
<p>
{title} {name}
</p>
);
}
Source: stackoverflow.com
Related Query
- How to specify (optional) default props with TypeScript for stateless, functional React components?
- How should I declare a Stateless Functional Component with Typescript in React?
- Fixing " 'Component' does not have any construct or call signatures." error for default props with Typescript
- How to set default value of props if not passed to functional component in NextJS using Typescript
- How to destructure props in stateless component (react) with default values into a variable and apply spread operator with that variable in JSX?
- router props and custom props with typescript react router dom for functional components
- How to declare different state and props for subclasses on react with typescript
- How to specify a function as an optional parameter to a hook with a default value
- Using Typescript generics for React Functional Components with eslint props validation
- How do I provide default values to optional nested props of type Object in typescript + React?
- How can I set default values for props on a React TypeScript component?
- What's wrong with the default value for a props of a functional component
- How create React Typescript component with required and optional values but required value without default value?
- How type material ui props for custom PopperComponent with Typescript
- React functional component with spread operator for props using typescript
- How to get classname or props from NavLink to use with google tag manager with react and redux in a stateless functional component?
- React, Material-UI: How to composition functional component with customized props using typescript
- How do I establish default props for functional React components
- How to implement an props interface for conditions with styled components in React with Typescript
- How to use children with React Stateless Functional Component in TypeScript?
- How do you provide default props for nested shape in React?
- How to specify a constructor with a functional component (fat arrow syntax)?
- How do I create a TypeScript type definition for a stateless React component?
- How to declare default props in react functional component
- Eslint: Problem with default props in functional component (Typescript - React)
- How to specify function parameters for React component callback with TypeScript?
- How to set navigationOptions on stateless component with Typescript
- How to set React default props for object type
- How to extend a native's component's props TypeScript interface in a stateless, functional component in React Native?
- How to use typescript with the definition of custom styles for a select using react-select
More Query from same tag
- How to access this.context.router (ReactJS)
- Why my render method is react called twice
- React toggling between clickable words that pull up <Elements/>
- Add attribuites to JSX.Element after declaration
- Passing parameters to a react component
- @apollo/client TypeError: link.request is not a function
- Is there a way to change the background colour of the view for 1 second whenever the state changes in react native?
- How to tell React ts component that a nullable state is guaranteed not to be null so that we don't have to confirm over and over?
- Mobx doesn't re-render React component
- ReactErrorUtils.invokeGuardedCallback in React fires event repeatedly in IE browser
- Passing onChange events through the state
- How to update component based on container's state change
- which is the correct way while using props in functional component in react
- How to make Jest wait for state to update - React / Jest / Enzyme
- How can I use react-spring useTransition to go from left to right or viceversa
- getting error: Cannot read property state of undefined
- react-step-progress bar styling customization
- How to make React Material grid responsive?
- Changing Bootstrap's responsiveness
- How to pass react component into dangerouslySetInnerHtml?
- Uncaught TypeError: equipo.data is undefined using React
- How to add multiple event handlers to same event in React.js
- Placing a picture next to a title for a react bootstrap Tab
- A recursive interface for a React Typescript component
- How do I set state for dynamically generated items in React?
- Material UI: Popover breaks when using onMouseLeave prop
- redux form validation with dynamic field id
- React Hooks: State Is Not Updating in Function
- How to use jQuery plugins in React, Riot 2.0
- Why is my react project crashing when updating from react-scripts 3.2.0 to 3.3.0?