Certainly! Refactoring your RoutineCreationScreen can greatly enhance its maintainability, readability, and scalability. Below is a refactored version of your code with the following improvements:
- Modular Components: Each step is broken down into its own component, making the codebase easier to manage and understand.
- State Management with
useReducer: Instead of multiple useState hooks, useReducer provides a more predictable and scalable state management solution, especially with complex nested state.
- Dynamic Step Rendering: Steps are defined in an array, allowing for dynamic rendering and easier reordering or addition/removal of steps.
- Validation Logic: Centralized validation logic for each step to ensure data integrity.
- Helper Functions: Utilities like
capitalizeFirstLetter are moved to a separate file for better organization.
Directory Structure
For better organization, the refactored code is divided into multiple files. Here's a suggested directory structure:
/components
/RoutineCreation
/steps
FitnessGoalsStep.js
ScheduleStep.js
ExercisesStep.js
RestRecoveryStep.js
ReviewStep.js
RoutineCreationScreen.js
RoutineCreationReducer.js
utils.js
RoutineCreationStyles.js
/context
AuthContext.js
1. RoutineCreationReducer.js
This file contains the reducer logic for managing the routineData state.
// RoutineCreationReducer.js
export const initialRoutineData = {
goal: '',
customGoal: '',
schedule: {
frequency: '',
duration: '',
preferredDays: [],
timeOfDay: '',
intensity: '',
},
exercises: [],
rest: {
restDays: [],
cooldownRoutine: [],
restBetweenSets: '',
},
routineName: '',
};
export const routineReducer = (state, action) => {
switch (action.type) {
case 'SET_GOAL':
return { ...state, goal: action.payload };
case 'SET_CUSTOM_GOAL':
return { ...state, customGoal: action.payload };
case 'SET_SCHEDULE':
return {
...state,
schedule: { ...state.schedule, [action.field]: action.payload },
};
case 'TOGGLE_PREFERRED_DAY':
const day = action.payload;
const preferredDays = state.schedule.preferredDays.includes(day)
? state.schedule.preferredDays.filter((d) => d !== day)
: [...state.schedule.preferredDays, day];
return {
...state,
schedule: { ...state.schedule, preferredDays },
};
case 'TOGGLE_REST_DAY':
const restDay = action.payload;
const restDays = state.rest.restDays.includes(restDay)
? state.rest.restDays.filter((d) => d !== restDay)
: [...state.rest.restDays, restDay];
return {
...state,
rest: { ...state.rest, restDays },
};
case 'SET_REST':
return {
...state,
rest: { ...state.rest, [action.field]: action.payload },
};
case 'SET_ROUTINE_NAME':
return { ...state, routineName: action.payload };
case 'SET_EXERCISES':
return { ...state, exercises: action.payload };
default:
return state;
}
};
2. utils.js
Utility functions used across multiple components.
// utils.js
export const capitalizeFirstLetter = (string) => {
if (!string) return '';
return string.charAt(0).toUpperCase() + string.slice(1);
};
3. Step Components
Each step is encapsulated in its own component for better modularity.
a. FitnessGoalsStep.js
// FitnessGoalsStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, Chip, TextInput, useTheme } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { capitalizeFirstLetter } from '../utils';
const FitnessGoalsStep = ({ routineData, dispatch, styles }) => {
const theme = useTheme();
const fitnessGoals = [
{ label: 'Build Muscle', value: 'muscle', icon: 'dumbbell' },
{ label: 'Lose Weight', value: 'weight', icon: 'scale' },
{ label: 'Increase Flexibility', value: 'flexibility', icon: 'yoga' },
{ label: 'Improve Endurance', value: 'endurance', icon: 'run' },
{ label: 'Toning', value: 'toning', icon: 'human' },
{ label: 'General Fitness', value: 'general', icon: 'heart-pulse' },
{ label: 'Custom Goal', value: 'custom', icon: 'pencil' },
];
const updateGoal = (value) => {
dispatch({ type: 'SET_GOAL', payload: value });
if (value !== 'custom') {
dispatch({ type: 'SET_CUSTOM_GOAL', payload: '' });
}
};
const updateCustomGoal = (text) => {
dispatch({ type: 'SET_CUSTOM_GOAL', payload: text });
};
return (
<View>
<Text style={styles.stepTitle}>Select Your Fitness Goals</Text>
<View style={styles.goalsContainer}>
{fitnessGoals.map((goal) => (
<Chip
key={goal.value}
onPress={() => updateGoal(goal.value)}
selected={routineData.goal === goal.value}
style={[
styles.goalChip,
routineData.goal === goal.value && { backgroundColor: theme.colors.primary },
]}
selectedColor={theme.colors.primary}
textStyle={{ color: routineData.goal === goal.value ? '#fff' : theme.colors.primary }}
icon={() => (
<Icon
name={goal.icon}
size={20}
color={routineData.goal === goal.value ? '#fff' : theme.colors.primary}
/>
)}
>
{goal.label}
</Chip>
))}
</View>
{routineData.goal === 'custom' && (
<TextInput
label="Custom Goal"
value={routineData.customGoal}
onChangeText={updateCustomGoal}
style={styles.input}
mode="outlined"
placeholder="Enter your custom goal"
theme={{ colors: { primary: theme.colors.primary, background: theme.colors.background } }}
/>
)}
</View>
);
};
export default FitnessGoalsStep;
b. ScheduleStep.js
// ScheduleStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, Chip, TextInput, useTheme } from 'react-native-paper';
import RNPickerSelect from 'react-native-picker-select';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
const ScheduleStep = ({ routineData, dispatch, styles }) => {
const theme = useTheme();
const updateSchedule = (field, value) => {
dispatch({ type: 'SET_SCHEDULE', field, payload: value });
};
const togglePreferredDay = (day) => {
dispatch({ type: 'TOGGLE_PREFERRED_DAY', payload: day });
};
const frequencies = [
{ label: '1 day per week', value: '1' },
{ label: '2 days per week', value: '2' },
{ label: '3 days per week', value: '3' },
{ label: '4 days per week', value: '4' },
{ label: '5 days per week', value: '5' },
{ label: '6 days per week', value: '6' },
{ label: '7 days per week', value: '7' },
];
const durations = [
{ label: '30 minutes', value: '30' },
{ label: '45 minutes', value: '45' },
{ label: '60 minutes', value: '60' },
{ label: '90 minutes', value: '90' },
];
const timesOfDay = [
{ label: 'Morning', value: 'morning' },
{ label: 'Afternoon', value: 'afternoon' },
{ label: 'Evening', value: 'evening' },
];
const intensities = [
{ label: 'Low', value: 'low' },
{ label: 'Medium', value: 'medium' },
{ label: 'High', value: 'high' },
];
return (
<View>
<Text style={styles.stepTitle}>Choose Your Workout Schedule</Text>
<Text style={styles.inputLabel}>Workout Frequency</Text>
<RNPickerSelect
onValueChange={(value) => updateSchedule('frequency', value)}
items={frequencies}
placeholder={{ label: 'Select workout frequency', value: null }}
value={routineData.schedule.frequency}
style={styles.picker}
useNativeAndroidPickerStyle={false}
Icon={() => <Icon name="chevron-down" size={20} color={theme.colors.text} />}
/>
<Text style={styles.inputLabel}>Workout Duration</Text>
<RNPickerSelect
onValueChange={(value) => updateSchedule('duration', value)}
items={durations}
placeholder={{ label: 'Select workout duration', value: null }}
value={routineData.schedule.duration}
style={styles.picker}
useNativeAndroidPickerStyle={false}
Icon={() => <Icon name="chevron-down" size={20} color={theme.colors.text} />}
/>
<Text style={styles.inputLabel}>Preferred Days</Text>
<View style={styles.daysContainer}>
{['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map((day) => (
<Chip
key={day}
onPress={() => togglePreferredDay(day)}
selected={routineData.schedule.preferredDays.includes(day)}
style={[
styles.dayChip,
routineData.schedule.preferredDays.includes(day) && {
backgroundColor: theme.colors.primary,
},
]}
selectedColor={theme.colors.primary}
textStyle={{
color: routineData.schedule.preferredDays.includes(day)
? '#fff'
: theme.colors.primary,
}}
>
{day}
</Chip>
))}
</View>
<Text style={styles.inputLabel}>Time of Day</Text>
<RNPickerSelect
onValueChange={(value) => updateSchedule('timeOfDay', value)}
items={timesOfDay}
placeholder={{ label: 'Select time of day', value: null }}
value={routineData.schedule.timeOfDay}
style={styles.picker}
useNativeAndroidPickerStyle={false}
Icon={() => <Icon name="chevron-down" size={20} color={theme.colors.text} />}
/>
<Text style={styles.inputLabel}>Intensity</Text>
<RNPickerSelect
onValueChange={(value) => updateSchedule('intensity', value)}
items={intensities}
placeholder={{ label: 'Select intensity level', value: null }}
value={routineData.schedule.intensity}
style={styles.picker}
useNativeAndroidPickerStyle={false}
Icon={() => <Icon name="chevron-down" size={20} color={theme.colors.text} />}
/>
</View>
);
};
export default ScheduleStep;
c. ExercisesStep.js
// ExercisesStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, useTheme } from 'react-native-paper';
const ExercisesStep = ({ routineData, dispatch, styles }) => {
const theme = useTheme();
// Placeholder: Implement exercise selection logic here
return (
<View>
<Text style={styles.stepTitle}>Select Your Exercises</Text>
<Text style={{ color: theme.colors.text }}>
Implement exercise selection here. You can include search functionality,
categories, and selection of multiple exercises.
</Text>
</View>
);
};
export default ExercisesStep;
d. RestRecoveryStep.js
// RestRecoveryStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, Chip, TextInput, useTheme } from 'react-native-paper';
import { capitalizeFirstLetter } from '../utils';
const RestRecoveryStep = ({ routineData, dispatch, styles }) => {
const theme = useTheme();
const toggleRestDay = (day) => {
dispatch({ type: 'TOGGLE_REST_DAY', payload: day });
};
const updateRest = (field, value) => {
dispatch({ type: 'SET_REST', field, payload: value });
};
return (
<View>
<Text style={styles.stepTitle}>Configure Rest & Recovery</Text>
<Text style={styles.inputLabel}>Rest Days</Text>
<View style={styles.daysContainer}>
{['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map((day) => (
<Chip
key={day}
onPress={() => toggleRestDay(day)}
selected={routineData.rest.restDays.includes(day)}
style={[
styles.dayChip,
routineData.rest.restDays.includes(day) && {
backgroundColor: theme.colors.primary,
},
]}
selectedColor={theme.colors.primary}
textStyle={{
color: routineData.rest.restDays.includes(day)
? '#fff'
: theme.colors.primary,
}}
>
{day}
</Chip>
))}
</View>
<Text style={styles.inputLabel}>Cooldown Routine</Text>
{/* Placeholder: Implement cooldown routine selection here */}
<Text style={{ color: theme.colors.text }}>
Implement cooldown routine selection here. You can include predefined cooldowns or allow users to create their own.
</Text>
<Text style={styles.inputLabel}>Rest Between Sets (seconds)</Text>
<TextInput
label="Rest Between Sets"
value={routineData.rest.restBetweenSets}
onChangeText={(text) => updateRest('restBetweenSets', text)}
style={styles.input}
mode="outlined"
keyboardType="numeric"
placeholder="e.g., 30"
theme={{ colors: { primary: theme.colors.primary, background: theme.colors.background } }}
/>
</View>
);
};
export default RestRecoveryStep;
e. ReviewStep.js
// ReviewStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, Card, useTheme } from 'react-native-paper';
import { capitalizeFirstLetter } from '../utils';
const ReviewStep = ({ routineData, fitnessGoals, styles }) => {
const theme = useTheme();
const getGoalLabel = () => {
if (routineData.goal === 'custom') {
return routineData.customGoal;
}
const goal = fitnessGoals.find((g) => g.value === routineData.goal);
return goal ? goal.label : 'N/A';
};
return (
<View>
<Text style={styles.stepTitle}>Review Your Routine</Text>
<Card style={styles.reviewCard}>
<Card.Title title="Routine Name" />
<Card.Content>
<Text>{routineData.routineName || 'N/A'}</Text>
</Card.Content>
</Card>
<Card style={styles.reviewCard}>
<Card.Title title="Fitness Goal" />
<Card.Content>
<Text>{getGoalLabel() || 'N/A'}</Text>
</Card.Content>
</Card>
<Card style={styles.reviewCard}>
<Card.Title title="Schedule" />
<Card.Content>
<Text>Frequency: {routineData.schedule.frequency} days/week</Text>
<Text>Duration: {routineData.schedule.duration} minutes</Text>
<Text>
Preferred Days: {routineData.schedule.preferredDays.join(', ') || 'N/A'}
</Text>
<Text>
Time of Day: {capitalizeFirstLetter(routineData.schedule.timeOfDay) || 'N/A'}
</Text>
<Text>
Intensity: {capitalizeFirstLetter(routineData.schedule.intensity) || 'N/A'}
</Text>
</Card.Content>
</Card>
{/* Add Cards for Exercises and Rest & Recovery as they are implemented */}
</View>
);
};
export default ReviewStep;
4. RoutineCreationStyles.js
Styles are centralized in this file, parameterized by the theme.
// RoutineCreationStyles.js
const getStyles = (theme) => ({
container: {
flex: 1,
backgroundColor: theme.colors.background,
},
contentContainer: {
padding: 16,
},
progressBar: {
marginBottom: 16,
},
stepTitle: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
color: theme.colors.text,
},
goalsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
marginBottom: 16,
},
goalChip: {
margin: 4,
},
input: {
marginTop: 16,
marginBottom: 16,
},
picker: {
inputIOS: {
fontSize: 16,
paddingVertical: 12,
paddingHorizontal: 10,
borderWidth: 1,
borderColor: theme.colors.disabled,
borderRadius: 4,
color: theme.colors.text,
paddingRight: 30, // to ensure the text is never behind the icon
marginBottom: 16,
},
inputAndroid: {
fontSize: 16,
paddingHorizontal: 10,
paddingVertical: 8,
borderWidth: 0.5,
borderColor: theme.colors.disabled,
borderRadius: 8,
color: theme.colors.text,
paddingRight: 30, // to ensure the text is never behind the icon
marginBottom: 16,
},
iconContainer: {
top: 10,
right: 12,
},
},
daysContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
marginBottom: 16,
},
dayChip: {
margin: 4,
},
navigationContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 24,
},
navButton: {
flex: 1,
marginHorizontal: 4,
},
inputLabel: {
fontSize: 16,
marginBottom: 8,
color: theme.colors.text,
},
reviewCard: {
marginBottom: 16,
},
});
export default getStyles;
5. RoutineCreationScreen.js
The main screen orchestrating all steps with dynamic rendering.
// RoutineCreationScreen.js
import React, { useReducer, useContext } from 'react';
import { View, ScrollView, Alert } from 'react-native';
import {
Text,
Button,
ProgressBar,
useTheme,
} from 'react-native-paper';
import { AuthContext } from '../../context/AuthContext';
import getStyles from './RoutineCreationStyles';
import { routineReducer, initialRoutineData } from './RoutineCreationReducer';
import FitnessGoalsStep from './steps/FitnessGoalsStep';
import ScheduleStep from './steps/ScheduleStep';
import ExercisesStep from './steps/ExercisesStep';
import RestRecoveryStep from './steps/RestRecoveryStep';
import ReviewStep from './steps/ReviewStep';
const STEPS = {
FITNESS_GOALS: 0,
SCHEDULE: 1,
EXERCISES: 2,
REST_RECOVERY: 3,
REVIEW: 4,
};
const RoutineCreationScreen = ({ navigation }) => {
const theme = useTheme();
const styles = getStyles(theme);
const { user } = useContext(AuthContext);
const [currentStep, setCurrentStep] = React.useState(STEPS.FITNESS_GOALS);
const [routineData, dispatch] = useReducer(routineReducer, initialRoutineData);
const fitnessGoals = [
{ label: 'Build Muscle', value: 'muscle', icon: 'dumbbell' },
{ label: 'Lose Weight', value: 'weight', icon: 'scale' },
{ label: 'Increase Flexibility', value: 'flexibility', icon: 'yoga' },
{ label: 'Improve Endurance', value: 'endurance', icon: 'run' },
{ label: 'Toning', value: 'toning', icon: 'human' },
{ label: 'General Fitness', value: 'general', icon: 'heart-pulse' },
{ label: 'Custom Goal', value: 'custom', icon: 'pencil' },
];
const steps = [
{
key: STEPS.FITNESS_GOALS,
title: 'Fitness Goals',
component: (
<FitnessGoalsStep
routineData={routineData}
dispatch={dispatch}
styles={styles}
/>
),
validate: () => {
if (!routineData.goal) {
Alert.alert('Validation Error', 'Please select a fitness goal.');
return false;
}
if (routineData.goal === 'custom' && !routineData.customGoal.trim()) {
Alert.alert('Validation Error', 'Please enter your custom goal.');
return false;
}
return true;
},
},
{
key: STEPS.SCHEDULE,
title: 'Schedule',
component: (
<ScheduleStep
routineData={routineData}
dispatch={dispatch}
styles={styles}
/>
),
validate: () => {
const { frequency, duration, preferredDays, timeOfDay, intensity } =
routineData.schedule;
if (
!frequency ||
!duration ||
preferredDays.length === 0 ||
!timeOfDay ||
!intensity
) {
Alert.alert('Validation Error', 'Please complete all schedule fields.');
return false;
}
return true;
},
},
{
key: STEPS.EXERCISES,
title: 'Exercises',
component: (
<ExercisesStep
routineData={routineData}
dispatch={dispatch}
styles={styles}
/>
),
validate: () => {
if (routineData.exercises.length === 0) {
Alert.alert('Validation Error', 'Please select at least one exercise.');
return false;
}
return true;
},
},
{
key: STEPS.REST_RECOVERY,
title: 'Rest & Recovery',
component: (
<RestRecoveryStep
routineData={routineData}
dispatch={dispatch}
styles={styles}
/>
),
validate: () => {
const { restDays, restBetweenSets } = routineData.rest;
if (restDays.length === 0 || !restBetweenSets) {
Alert.alert('Validation Error', 'Please complete all rest & recovery fields.');
return false;
}
return true;
},
},
{
key: STEPS.REVIEW,
title: 'Review',
component: (
<ReviewStep
routineData={routineData}
fitnessGoals={fitnessGoals}
styles={styles}
/>
),
validate: () => {
if (!routineData.routineName.trim()) {
Alert.alert('Validation Error', 'Please provide a name for your routine.');
return false;
}
return true;
},
},
];
const handleNext = () => {
if (!steps[currentStep].validate()) return;
if (currentStep < STEPS.REVIEW) {
setCurrentStep(currentStep + 1);
} else {
// Handle routine creation logic here
Alert.alert('Success', 'Routine created successfully!');
navigation.goBack();
}
};
const handleBack = () => {
if (currentStep > STEPS.FITNESS_GOALS) {
setCurrentStep(currentStep - 1);
} else {
navigation.goBack();
}
};
return (
<ScrollView
style={styles.container}
contentContainerStyle={styles.contentContainer}
>
<ProgressBar
progress={(currentStep + 1) / steps.length}
color={theme.colors.primary}
style={styles.progressBar}
/>
{steps[currentStep].component}
<View style={styles.navigationContainer}>
<Button
mode="outlined"
onPress={handleBack}
style={styles.navButton}
color={theme.colors.primary}
>
{currentStep === STEPS.FITNESS_GOALS ? 'Cancel' : 'Back'}
</Button>
<Button
mode="contained"
onPress={handleNext}
style={styles.navButton}
color={theme.colors.primary}
>
{currentStep === STEPS.REVIEW ? 'Create Routine' : 'Next'}
</Button>
</View>
</ScrollView>
);
};
export default RoutineCreationScreen;
6. Additional Considerations
a. Exercise Selection Implementation
The ExercisesStep currently contains a placeholder. Depending on your requirements, you might want to implement:
- Search Functionality: Allow users to search for exercises.
- Categories: Group exercises by muscle groups or equipment.
- Selection Mechanism: Let users select multiple exercises, possibly with checkboxes or chips.
b. Cooldown Routine Selection
Similar to exercises, you can implement functionalities to select or create cooldown routines in the RestRecoveryStep.
c. Handling Routine Creation
In the handleNext function, replace the Alert with actual logic to save the routine, such as API calls or updating context/global state.
d. Validation Enhancements
Depending on your app's requirements, you might need more robust validation, possibly using libraries like yup in combination with Formik for form handling.
7. Benefits of the Refactored Code
- Readability: Each component has a single responsibility, making it easier to understand.
- Maintainability: Changes in one step won't affect others, reducing the risk of introducing bugs.
- Scalability: Adding new steps or modifying existing ones becomes straightforward.
- Reusability: Shared components and styles can be reused across different parts of the app.
- State Management: Using
useReducer provides a clearer and more manageable state transition logic.
8. Final Thoughts
Refactoring large components by breaking them down into smaller, more manageable pieces is a best practice in React development. It not only makes the codebase cleaner but also facilitates easier testing and future enhancements. The above refactored code should serve as a solid foundation for your Routine Creation feature in your Expo mobile app.