Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  125] [ 4]  / answers: 1 / hits: 183227  / 8 Years ago, mon, october 24, 2016, 12:00:00

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.


More From » reactjs

 Answers
11

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;

[#60305] Thursday, October 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harveys

Total Points: 113
Total Questions: 88
Total Answers: 79

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;