How do I turn this into a PureComponent? import React, { memo } from "react"; import {…
- User
How do I turn this into a PureComponent?
import React, { memo } from "react"; import { View } from 'react-native'; import { Card, Chip, Text, useTheme } from 'react-native-paper';
import FoodData from './FoodData';
// import { Avatar, Button, Card, CardActionArea, CardActions, CardContent, CardHeader, CardMedia, Collapse, IconButton, Typography } from '@mui/material';
const timeNow = Date.now();
export type Props = { addMessage: (string) => void, data: FoodData; };
const FoodPost = ({ addMessage, data, ...rest }: Props) => { // Not snackbar const [expanded, setExpanded] = React.useState(false); const handlePress = () => setExpanded(!expanded); const theme = useTheme(); return ( <View style={{ margin: 8 }}> <Card mode="contained" style={{ backgroundColor: theme.colors.inverseOnSurface }} onPress={handlePress}> <Card.Title titleStyle={{ fontWeight: 'bold', paddingTop: 8 }} titleVariant="titleLarge" titleNumberOfLines={2} style={{ flex: 3 }} title={data.location} subtitle={getTimeAgo(data.date)} rightStyle={{ paddingRight: 20 }} right={(props) => < 3 miles} /> {/* Show chips /} <Card.Content style={{ paddingTop: 8, flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}> {data.transportation && <Chip compact onPress={() => addMessage("This item requires you to leave campus or use transportation")} icon="car">Off-Campus} {data.phoneNeeded && <Chip compact onPress={() => addMessage("Bring your phone (fill out form, show voucher, etc.)")} icon="cellphone">Need Phone} {data.doorAccess && <Chip compact onPress={() => addMessage("Food is behind locked doors or in a private event")} icon="door-sliding-lock">Entry Needed} </Card.Content> {/ Body */} <Card.Content style={{ paddingTop: 8 }}> {data.details} </Card.Content> ); }
// This is supposed to help with performance export default memo(FoodPost);
const getTimeAgo = (date) => { const now = new Date(); const elapsed = now.getTime() - new Date(date).getTime();
const minutes = Math.floor(elapsed / 60000); const hours = Math.floor(elapsed / 3600000); const days = Math.floor(elapsed / 86400000); const weeks = Math.floor(elapsed / 604800000); const months = Math.floor(elapsed / 2629800000); const years = Math.floor(elapsed / 31557600000); if (minutes < 1) { return 'just now'; } else if (minutes < 60) { return `${minutes} minute${minutes === 1 ? '' : 's'} ago`; } else if (hours < 24) { return `${hours} hour${hours === 1 ? '' : 's'} ago`; } else if (days < 7) { return `${days} day${days === 1 ? '' : 's'} ago`; } else if (weeks < 4) { return `${weeks} week${weeks === 1 ? '' : 's'} ago`; } else if (months < 12) { return `${months} month${months === 1 ? '' : 's'} ago`; } else { return `${years} year${years === 1 ? '' : 's'} ago`; }};
- Assistant
To convert the
FoodPostcomponent into aPureComponent, you don't necessarily need to usememo. You can turn it into a class component that extendsReact.PureComponent. APureComponentperforms a shallow comparison on the props and state to decide if a re-render is necessary. This can help improve performance by preventing unnecessary renders when the props have not changed.Here's how you can modify the
FoodPostcomponent to be aPureComponent:import React, { PureComponent } from 'react'; import { View } from 'react-native'; import { Card, Chip, Text, useTheme } from 'react-native-paper'; import FoodData from './FoodData'; // import { Avatar, Button, Card, CardActionArea, CardActions, CardContent, CardHeader, CardMedia, Collapse, IconButton, Typography } from '@mui/material'; const timeNow = Date.now(); export type Props = { addMessage: (string) => void, data: FoodData; }; class FoodPost extends PureComponent<Props> { constructor(props) { super(props); this.state = { expanded: false }; } handlePress = () => { this.setState(prevState => ({ expanded: !prevState.expanded })); }; render() { const { addMessage, data, ...rest } = this.props; const theme = useTheme(); return ( <View style={{ margin: 8 }}> <Card mode="contained" style={{ backgroundColor: theme.colors.inverseOnSurface }} onPress={this.handlePress}> <Card.Title titleStyle={{ fontWeight: 'bold', paddingTop: 8 }} titleVariant="titleLarge" titleNumberOfLines={2} style={{ flex: 3 }} title={data.location} subtitle={getTimeAgo(data.date)} rightStyle={{ paddingRight: 20 }} right={(props) => <Text>< 3 miles</Text>} /> {/* Show chips */} <Card.Content style={{ paddingTop: 8, flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}> {data.transportation && <Chip compact onPress={() => addMessage("This item requires you to leave campus or use transportation")} icon="car">Off-Campus</Chip>} {data.phoneNeeded && <Chip compact onPress={() => addMessage("Bring your phone (fill out form, show voucher, etc.)")} icon="cellphone">Need Phone</Chip>} {data.doorAccess && <Chip compact onPress={() => addMessage("Food is behind locked doors or in a private event")} icon="door-sliding-lock">Entry Needed</Chip>} </Card.Content> {/* Body */} <Card.Content style={{ paddingTop: 8 }}> <Text variant="bodyLarge">{data.details}</Text> </Card.Content> </Card> </View> ); } } export default FoodPost; const getTimeAgo = (date) => { const now = new Date(); const elapsed = now.getTime() - new Date(date).getTime(); const minutes = Math.floor(elapsed / 60000); const hours = Math.floor(elapsed / 3600000); const days = Math.floor(elapsed / 86400000); const weeks = Math.floor(elapsed / 604800000); const months = Math.floor(elapsed / 2629800000); const years = Math.floor(elapsed / 31557600000); if (minutes < 1) { return 'just now'; } else if (minutes < 60) { return `${minutes} minute${minutes === 1 ? '' : 's'} ago`; } else if (hours < 24) { return `${hours} hour${hours === 1 ? '' : 's'} ago`; } else if (days < 7) { return `${days} day${days === 1 ? '' : 's'} ago`; } else if (weeks < 4) { return `${weeks} week${weeks === 1 ? '' : 's'} ago`; } else if (months < 12) { return `${months} month${months === 1 ? '' : 's'} ago`; } else { return `${years} year${years === 1 ? '' : 's'} ago`; } };Summary of Changes:
- Converted the functional component into a class component.
- Extended
React.PureComponentinstead of usingmemo. - Moved the use of
useStatetothis.stateto manage the expanded state. - Converted the
handlePressfunction to an instance method. - In the
rendermethod, we retrievedpropsandstateto render the component.
However, it's worth noting that
useThemeis a hook and cannot be directly used within a class component. You might need to pass the theme as a prop or use the context APIs if you want to continue using a class component.