Certainly! Refactoring your RoutineCreationScreen to be more dynamic enhances maintainability, scalability, and readability. Below is a refactored version that incorporates the following improvements:
- Dynamic Step Configuration: Define steps in a configuration object to handle rendering dynamically.
- Modular Components: Break down each step into separate, reusable components.
- Utility Functions: Extract repeated logic into utility functions to reduce redundancy.
- Enhanced State Management: Use structured state updates for better clarity.
- Improved Validation: Centralize validation logic for each step.
Let's dive into the refactored code.
1. Step Configuration
Create a configuration object to define each step's title, component, and validation logic. This approach makes it easy to add, remove, or reorder steps without modifying the core logic.
// stepsConfig.js
import React from 'react';
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';
export const STEPS = [
{
id: 'FITNESS_GOALS',
title: 'Select Your Fitness Goals',
component: FitnessGoalsStep,
validate: (routineData) => {
const { goal, customGoal } = routineData;
if (!goal) return 'Please select a fitness goal.';
if (goal === 'custom' && !customGoal.trim()) return 'Please enter your custom goal.';
return null;
},
},
{
id: 'SCHEDULE',
title: 'Choose Your Workout Schedule',
component: ScheduleStep,
validate: (routineData) => {
const { frequency, duration, preferredDays, timeOfDay, intensity } = routineData.schedule;
if (!frequency || !duration || preferredDays.length === 0 || !timeOfDay || !intensity)
return 'Please complete all schedule fields.';
return null;
},
},
{
id: 'EXERCISES',
title: 'Select Your Exercises',
component: ExercisesStep,
validate: (routineData) => {
if (routineData.exercises.length === 0) return 'Please select at least one exercise.';
return null;
},
},
{
id: 'REST_RECOVERY',
title: 'Configure Rest & Recovery',
component: RestRecoveryStep,
validate: (routineData) => {
const { restDays, restBetweenSets } = routineData.rest;
if (restDays.length === 0 || !restBetweenSets) return 'Please complete all rest & recovery fields.';
return null;
},
},
{
id: 'REVIEW',
title: 'Review Your Routine',
component: ReviewStep,
validate: (routineData) => {
if (!routineData.routineName.trim()) return 'Please provide a name for your routine.';
return null;
},
},
];
2. Modular Step Components
Each step is now a separate component, enhancing readability and reusability.
2.1. FitnessGoalsStep.js
// steps/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 getStyles from '../RoutineCreationStyles';
const FitnessGoalsStep = ({ routineData, updateRoutineData, fitnessGoals }) => {
const theme = useTheme();
const styles = getStyles(theme);
return (
<View>
<Text style={styles.stepTitle}>Select Your Fitness Goals</Text>
<View style={styles.goalsContainer}>
{fitnessGoals.map((goal) => (
<Chip
key={goal.value}
onPress={() => updateRoutineData('goal', 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={(text) => updateRoutineData('customGoal', text)}
style={styles.input}
mode="outlined"
placeholder="Enter your custom goal"
theme={{ colors: { primary: theme.colors.primary, background: theme.colors.background } }}
/>
)}
</View>
);
};
export default FitnessGoalsStep;
2.2. ScheduleStep.js
// steps/ScheduleStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, Chip, TextInput } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import RNPickerSelect from 'react-native-picker-select';
import getStyles from '../RoutineCreationStyles';
const ScheduleStep = ({ routineData, updateSchedule, togglePreferredDay }) => {
const theme = useTheme();
const styles = getStyles(theme);
const frequencyOptions = Array.from({ length: 7 }, (_, i) => ({
label: `${i + 1} day${i > 0 ? 's' : ''} per week`,
value: `${i + 1}`,
}));
const durationOptions = [
{ label: '30 minutes', value: '30' },
{ label: '45 minutes', value: '45' },
{ label: '60 minutes', value: '60' },
{ label: '90 minutes', value: '90' },
];
const timeOfDayOptions = [
{ label: 'Morning', value: 'morning' },
{ label: 'Afternoon', value: 'afternoon' },
{ label: 'Evening', value: 'evening' },
];
const intensityOptions = [
{ 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={frequencyOptions}
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={durationOptions}
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={timeOfDayOptions}
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={intensityOptions}
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;
2.3. ExercisesStep.js
// steps/ExercisesStep.js
import React from 'react';
import { View } from 'react-native';
import { Text } from 'react-native-paper';
import getStyles from '../RoutineCreationStyles';
const ExercisesStep = () => {
const theme = useTheme();
const styles = getStyles(theme);
return (
<View>
<Text style={styles.stepTitle}>Select Your Exercises</Text>
{/* Placeholder for exercise selection UI */}
<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;
2.4. RestRecoveryStep.js
// steps/RestRecoveryStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, Chip, TextInput, useTheme } from 'react-native-paper';
import getStyles from '../RoutineCreationStyles';
const RestRecoveryStep = ({ routineData, updateRest, toggleRestDay }) => {
const theme = useTheme();
const styles = getStyles(theme);
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 for cooldown routine selection */}
<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;
2.5. ReviewStep.js
// steps/ReviewStep.js
import React from 'react';
import { View } from 'react-native';
import { Text, Card, useTheme } from 'react-native-paper';
import getStyles from '../RoutineCreationStyles';
const ReviewStep = ({ routineData, fitnessGoals }) => {
const theme = useTheme();
const styles = getStyles(theme);
const capitalizeFirstLetter = (string) => {
if (!string) return '';
return string.charAt(0).toUpperCase() + string.slice(1);
};
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>
{routineData.goal === 'custom'
? routineData.customGoal
: fitnessGoals.find((goal) => goal.value === routineData.goal)?.label || 'N/A'}
</Text>
</Card.Content>
</Card>
<Card style={styles.reviewCard}>
<Card.Title title="Schedule" />
<Card.Content>
<Text>Frequency: {routineData.schedule.frequency} day(s)/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;
3. Utility Functions
Extract repeated logic such as toggling days into utility functions to keep components clean.
// utils/toggleDay.js
export const toggleDay = (currentDays, day) => {
if (currentDays.includes(day)) {
return currentDays.filter((d) => d !== day);
}
return [...currentDays, day];
};
4. Refactored RoutineCreationScreen
Combine everything into the main screen component, leveraging the dynamic step configuration and modular components.
// RoutineCreationScreen.js
import React, { useState, useContext } from 'react';
import { View, ScrollView, Alert } from 'react-native';
import { Button, ProgressBar, Text, useTheme } from 'react-native-paper';
import { AuthContext } from '../../context/AuthContext';
import { STEPS } from './stepsConfig';
import getStyles from './RoutineCreationStyles';
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';
import { toggleDay } from './utils/toggleDay';
const RoutineCreationScreen = ({ navigation }) => {
const theme = useTheme();
const styles = getStyles(theme);
const { user } = useContext(AuthContext);
const [currentStepIndex, setCurrentStepIndex] = useState(0);
const [routineData, setRoutineData] = useState({
goal: '',
customGoal: '',
schedule: {
frequency: '',
duration: '',
preferredDays: [],
timeOfDay: '',
intensity: '',
},
exercises: [],
rest: {
restDays: [],
cooldownRoutine: [],
restBetweenSets: '',
},
routineName: '',
});
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 updateRoutineData = (field, value) => {
setRoutineData((prev) => ({
...prev,
[field]: value,
}));
};
const updateSchedule = (field, value) => {
setRoutineData((prev) => ({
...prev,
schedule: {
...prev.schedule,
[field]: value,
},
}));
};
const updateRest = (field, value) => {
setRoutineData((prev) => ({
...prev,
rest: {
...prev.rest,
[field]: value,
},
}));
};
const togglePreferredDay = (day) => {
setRoutineData((prev) => ({
...prev,
schedule: {
...prev.schedule,
preferredDays: toggleDay(prev.schedule.preferredDays, day),
},
}));
};
const toggleRestDay = (day) => {
setRoutineData((prev) => ({
...prev,
rest: {
...prev.rest,
restDays: toggleDay(prev.rest.restDays, day),
},
}));
};
const handleNext = () => {
const currentStep = STEPS[currentStepIndex];
const validationError = currentStep.validate(routineData);
if (validationError) {
Alert.alert('Validation Error', validationError);
return;
}
if (currentStepIndex < STEPS.length - 1) {
setCurrentStepIndex(currentStepIndex + 1);
} else {
// Handle routine creation logic here
Alert.alert('Success', 'Routine created successfully!');
navigation.goBack();
}
};
const handleBack = () => {
if (currentStepIndex > 0) {
setCurrentStepIndex(currentStepIndex - 1);
} else {
navigation.goBack();
}
};
const CurrentStepComponent = STEPS[currentStepIndex].component;
return (
<ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
<ProgressBar
progress={(currentStepIndex + 1) / STEPS.length}
color={theme.colors.primary}
style={styles.progressBar}
/>
<CurrentStepComponent
routineData={routineData}
updateRoutineData={updateRoutineData}
updateSchedule={updateSchedule}
updateRest={updateRest}
togglePreferredDay={togglePreferredDay}
toggleRestDay={toggleRestDay}
fitnessGoals={fitnessGoals}
/>
<View style={styles.navigationContainer}>
<Button
mode="outlined"
onPress={handleBack}
style={styles.navButton}
color={theme.colors.primary}
>
{currentStepIndex === 0 ? 'Cancel' : 'Back'}
</Button>
<Button
mode="contained"
onPress={handleNext}
style={styles.navButton}
color={theme.colors.primary}
>
{currentStepIndex === STEPS.length - 1 ? 'Create Routine' : 'Next'}
</Button>
</View>
</ScrollView>
);
};
export default RoutineCreationScreen;
5. Stylesheet
Ensure your styles are flexible and accommodate the dynamic layout. Here's an example of how your RoutineCreationStyles might look:
// RoutineCreationStyles.js
import { StyleSheet } from 'react-native';
const getStyles = (theme) =>
StyleSheet.create({
container: {
flex: 1,
backgroundColor: theme.colors.background,
},
contentContainer: {
padding: 16,
},
progressBar: {
height: 10,
borderRadius: 5,
marginBottom: 20,
},
stepTitle: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
color: theme.colors.text,
},
goalsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 10,
marginBottom: 20,
},
goalChip: {
margin: 4,
},
input: {
marginVertical: 10,
},
inputLabel: {
fontSize: 16,
marginBottom: 8,
color: theme.colors.text,
},
picker: {
inputIOS: {
fontSize: 16,
paddingVertical: 12,
paddingHorizontal: 10,
borderWidth: 1,
borderColor: theme.colors.placeholder,
borderRadius: 4,
color: theme.colors.text,
paddingRight: 30, // to ensure the text is never behind the icon
marginBottom: 20,
},
inputAndroid: {
fontSize: 16,
paddingHorizontal: 10,
paddingVertical: 8,
borderWidth: 0.5,
borderColor: theme.colors.placeholder,
borderRadius: 8,
color: theme.colors.text,
paddingRight: 30, // to ensure the text is never behind the icon
marginBottom: 20,
},
iconContainer: {
top: 10,
right: 12,
},
},
daysContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 10,
marginBottom: 20,
},
dayChip: {
margin: 4,
},
navigationContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 20,
},
navButton: {
flex: 1,
marginHorizontal: 5,
},
reviewCard: {
marginVertical: 10,
},
});
export default getStyles;
6. Utility Function for Toggling Days
As previously mentioned, utilize a utility function to handle day toggling logic.
// utils/toggleDay.js
export const toggleDay = (currentDays, day) => {
if (currentDays.includes(day)) {
return currentDays.filter((d) => d !== day);
}
return [...currentDays, day];
};
7. Folder Structure
For better organization, structure your files as follows:
RoutineCreationScreen/
│
├── stepsConfig.js
├── RoutineCreationScreen.js
├── RoutineCreationStyles.js
├── utils/
│ └── toggleDay.js
└── steps/
├── FitnessGoalsStep.js
├── ScheduleStep.js
├── ExercisesStep.js
├── RestRecoveryStep.js
└── ReviewStep.js
8. Additional Considerations
- Exercise Selection & Cooldown Routine: Implement these placeholders with actual functionality, potentially using search components, selection lists, or modals.
- Form Libraries: For more complex forms, consider using form management libraries like Formik with Yup for validation.
- State Management: If the state becomes too complex, integrating a state management library like Redux might be beneficial.
- Accessibility: Ensure that all interactive elements are accessible, with proper labeling and focus management.
- Testing: Implement unit and integration tests to ensure each component behaves as expected.
9. Final Notes
This refactored approach provides a more scalable and maintainable structure for your routine creation process. By compartmentalizing each step into its own component and centralizing the step configuration, you can effortlessly manage and extend the workflow as your application grows.
Feel free to adjust the styles and component implementations to better fit your specific design requirements and application logic.