JP.
JP.

Reputation: 1075

how to conditionally render styles in react native component?

I have a custom component that provides the rendered list of data when the data is available.

But when the data is not available in the example case below where data=[], I want to apply a different style to it.

return (
                        <FollowableArticleListTemplate
                            style={hasData}
                            title={ title }
                            data={ [] }
                            isFollowing={ isFollowing }
                            onToggleFollow={ id ? () => toggleSourceFollow(id, isFollowing, title) : null }
                            setListRef={ this.setListRef }
                            contentType="source"
                        />
                    );

What I'm looking for is something like this: style={hasData}

i.e if the data.length > 0 use this style for this component: style={hasData} otherwise use this style component: style={noData}

Upvotes: 0

Views: 46

Answers (1)

Ian Vasco
Ian Vasco

Reputation: 1340

This is easily achieved by using the ternary operator. First, you have to conditionally use data using state, not by giving its value directly into the component.

return (
                        <FollowableArticleListTemplate
                            style={myData.length > 0 ? hasData : noData}
                            title={ title }
                            data={myData}//this is your state
                            isFollowing={ isFollowing }
                            onToggleFollow={ id ? () => toggleSourceFollow(id, isFollowing, title) : null }
                            setListRef={ this.setListRef }
                            contentType="source"
                        />
                    );
    ```

Upvotes: 1

Related Questions