Search code examples
javascriptreact-nativereact-native-component

How can I convert stateless function to class component in react native


I am new in react native, I have been looking for how to convert this function to a class component in react native. Please I need help to convert the code below to react component.

import React from 'react';
import { View, Image, ScrollView } from 'react-native';

import styles from './styles';

export default ({captures=[]}) => (
    <ScrollView 
        horizontal={true}
        style={[styles.bottomToolbar, styles.galleryContainer]} 
    >
        {captures.map(({ uri }) => (
            <View style={styles.galleryImageContainer} key={uri}>
                <Image source={{ uri }} style={styles.galleryImage} />
            </View>
        ))}
    </ScrollView>
);

Solution

  • To turn this into a class component, just move the code into the class component's render method, and change references to props with references to this.props. For this component, no other changes are needed.

    export default class Example extends React.Component {
      render () {
        const { captures = [] } = this.props;
        return (
          <ScrollView 
            horizontal={true}
            style={[styles.bottomToolbar, styles.galleryContainer]} 
          >
            {captures.map(({ uri }) => (
              <View style={styles.galleryImageContainer} key={uri}>
                <Image source={{ uri }} style={styles.galleryImage} />
              </View>
            ))}
          </ScrollView>
        )
      }
    }