HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptreactCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptwithhowcomponentsforstatelessspecifyoptionalfunctionalreact

Problem

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) => (
    
        {props.title} {props.name}
    
);

export default Test;


Calling ` renders "Sir Lancelot" as expected, but ` results in nothing, when it should output
"Mr McGee".

Any help is greatly appreciated.

Solution

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 = (props) => (
    
        {props.title} {props.name}
    
);

Test.defaultProps = defaultProps;

export default Test;

Code Snippets

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;

Context

Stack Overflow Q#40209352, score: 170

Revisions (0)

No revisions yet.