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
- Redirect user if value in the redux store is not present from component
- NextJS, Socket.io: in the server-side, my third parameter which is a acknowledgement's callback returns to me: callback is not a function
- Unable to set required field in React js
- getInitialProps import data in Next.js
- PropTypes: array of one of the class instance
- Read more functionality: Too many re-renders. React limits the number of renders to prevent an infinite loop
- React functional components with hooks - getting response from function written in reducer
- "react-router-dom": "^6.3.0", when I click the action the URI is changing but component is not mounting
- Assertion on mocked function is failing
- HTML to PDF convert in react js using jsPDF not working
- Showing components on checkbox click in react
- UnhandledPromiseRejectionWarning: RangeError: Maximum call stack size exceeded
- How to render data from multiple tables from MySQL using React, Spring Boot?
- How to check in Next.js if a dynamic path does not exists and to return 404 after checking in database?
- React : Passing and retrieving data between parent and child using props and callbacks
- Getting ref to props.children by React.cloneElement returns always null
- How to update array using state in ReactJS
- Issue with useEffect in child component rendering several times based on parent setting states in its own useEffect
- Redux Can't Get State from Store
- React Router rendering 404 Not Found on reload
- How can I hide particular element in react list?
- ReactJS: How to read and write to a file
- jquery styling not working in react component
- Redux Form/Material UI form - sending binary files to the server
- Render Clappr player in ReactJS
- I need to set Fields to initial state after data added in table field onClick
- React/JavaScript, can someone explain why setState doesn't seem to correctly update the state during the function?
- React Chakra-UI slider returns undefined onChange
- React app error: `Uncaught TypeError: Cannot read property 'refs' of null`
- What type should I use for input react-bootstrap event with TypeScript?