Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify (optional) default props with TypeScript for stateless, functional React components?

I'm trying to create a stateless React component with optional props and defaultProps in Typescript (for a React Native project). This is trivial with vanilla JS, but I'm stumped as to how to achieve it in TypeScript.

With the following code:

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 = (props = defaultProps) => (     <Text>         {props.title} {props.name}     </Text> );  export default Test; 

Calling <Test title="Sir" name="Lancelot" /> renders "Sir Lancelot" as expected, but <Test /> results in nothing, when it should output "Mr McGee".

Any help is greatly appreciated.

like image 668
Matt Stow Avatar asked Oct 24 '16 00:10

Matt Stow


People also ask

How do you pass optional props in React TypeScript?

To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.

How do you define default props in React functional components?

For a React component created using the ES6 class syntax, you can set default props by adding a static property named defaultProps to the component class. The defaultProps static property should be set to an object representing the default props for the component.

Can a stateless component have props?

Stateful and Stateless Components In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props.


1 Answers

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; 
like image 65
Matt Stow Avatar answered Oct 02 '22 06:10

Matt Stow