Sign in
Log inSign up
Writing Stateless Components in React Native

Writing Stateless Components in React Native

Kashish Grover's photo
Kashish Grover
·Feb 27, 2018

Recently I learned how cool Stateless components are in React. So I thought to myself — how do I write them in React Native? Can I do it out of the box?

I went ahead and tried, and it works like a breeze! And in my opinion, this is the best way to go when you don’t need lifecycle methods in a component.

Some plus points which I noticed:

  1. Super easy to read and understand
  2. No ‘this’ keyword
  3. Great for presentational (not so dumb) components — a best practice
  4. Less code

I should stop typing and show the code which I made for you. :)

// Consider a situation where you pass data, a state, and your navigation as props to your child component.

const MyComponent = ({ loadingImages, data, navigation }) => {

  const loadNextPage = () => {
    navigation.navigate('NextPage');
  }

  return (
    <View>
    {
      loadingImages ?
      <ActivityIndicator />
      :
      <Image source={{ uri: data.image }} />
    }
      <View>
        <Text>{data.title}</Text>
        <Text>{data.subtitle}</Text>
      </View>
      <TouchableOpacity
        onPress={loadNextPage}
        activeOpacity={0.8}
      >
        <Text>Click here for next page.</Text>
      </TouchableOpacity>
    </View>
  );
};

export default MyComponent;

/*
USAGE in a Screen -- ParentScreen.js
Consider you called your API in the screen which loads a bunch of images. This data was then inserted into this.data object.
When the API gets called and the parent rerenders, so does the child. 

<MyComponent 
  loadingImages={this.state.loadingImages}  
  data={this.data}
  navigation={this.props.navigation}
/>
*/
Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct