Skip to content

Instantly share code, notes, and snippets.

@jakewtaylor
Created December 11, 2019 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakewtaylor/8c0fb15669f8f6db139a96d0b58d116a to your computer and use it in GitHub Desktop.
Save jakewtaylor/8c0fb15669f8f6db139a96d0b58d116a to your computer and use it in GitHub Desktop.

Template Component

Counter.tsx

import React, { useState, useCallback } from 'react';
import { View, Text, TextInput, TouchableHighlight } from 'react-native';
import { connect } from 'react-redux';
import { Dispatch } from 'redux';
import { styles } from './Counter.styles';

type ReduxStateProps = {
  count: number;
}

type ReduxDispatchProps = {
  increment(amount: number): void;
  decrement(amount: number): void;
}

type Props = {
  title?: string;
}

const Counter: React.FC<Props & ReduxStateProps & ReduxDispatchProps> = ({
  title = 'Counter',
  count,
  increment,
  decrement,
}) => {
  const [step, setStep] = useState(1);

  const handleStepChange = useCallback((newStep: string) => {
    setStep(parseInt(newStep, 10));
  }, []); 

  const handleIncrement = useCallback(() => {
    increment(step);
  }, [step]);

  const handleDecrement = useCallback(() => {
    decrement(step);
  }, [step]);

  return (
    <View>
      <Text style={styles.title}>{title}</Text>
      <Text style={styles.count}>{count}</Text>

      <TextInput
        keyboardType="numeric"
        value={step}
        onChangeText={handleStepChange}
      />

      <TouchableHighlight onPress={handleIncrement}>
        <Text>Increment</Text>
      </TouchableHighlight>

      <TouchableHighlight onPress={handleDecrement}>
        <Text>Decrement</Text>
      </TouchableHighlight>
    </View>
  );
}

const mapStateToProps = ({ count }: ReduxState): ReduxStateProps => ({
  count,
});

const mapDispatchToProps = (dispatch: Dispatch): ReduxDispatchProps => ({
  increment(amount: number) {
    dispatch(CounterActions.adjust(amount));
  },

  decrement(amount: number) {
    dispatch(CounterActions.adjust(amount * -1));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

Counter.styles.ts

import { StyleSheet } from 'react-native';

export const styles = StyleSheet.create({
  title: { /* styles */ },
  count: { /* styles */ },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment