Guy
Guy

Reputation: 13306

Putting the defaultProps before a stateless component definition for the sake of readability

Is there a way, for the sake of readability, to put the contextTypes and defaultProps before a stateless React component?

type TopBarProps = {
    children: string,
    color: string
};

TopBar.defaultProps = {
    color: "white"
};

TopBar.contextTypes = {
    locale: PropTypes.string,
    colors: PropTypes.object,
    i18n: PropTypes.object,
    fontFamily: PropTypes.object,
    scale: PropTypes.number,
    alignStyle: PropTypes.string,
    navMethods: PropTypes.object,
    token: PropTypes.string,
    arrowName: PropTypes.string,
    materialArrows: PropTypes.object
};

export const TopBar = (props: TopBarProps, context) => {
    const { colors } = context;

    styles = styles || initStyles(context);

    return (
        <View style={styles.container}>
            <View>
                <Menu color={colors.colorFont} />
            </View>
            <View>
                <TopLabel color={props.color}>{props.children}</TopLabel>
            </View>
        </View>
    );
};

Upvotes: 0

Views: 120

Answers (2)

Jemi Salo
Jemi Salo

Reputation: 3751

You can define them first as constants, then set them as fields of your component after defining it. Since they are appropriately named, it should be rather obvious to a reader what the constants will be used for.

const defaultProps = { ... }
const contextTypes = { ... }

export const TopBar = (props: TopBarProps, context) => { ... }

TopBar.defaultProps = defaultProps
TopBar.contextTypes = contextTypes

Upvotes: 1

Anton Harniakou
Anton Harniakou

Reputation: 880

Define a component using function syntax, like so:

export function TopBar(props: TopBarProps, context) {
    const { colors } = context;

    styles = styles || initStyles(context);

    return (
        <View style={styles.container}>
            <View>
                <Menu color={colors.colorFont} />
            </View>
            <View>
                <TopLabel color={props.color}>{props.children}</TopLabel>
            </View>
        </View>
    );
};

It should work because of the thing called hoisting

Upvotes: 0

Related Questions