How can I rewrite this component so it doesn't go against the rules of React? I'm calling the function renderButtonType()
inside of the render()
. Is that the correct way to conditionally render the component or is there a better way?
// Component: Button (Navigate)const ButtonNavigate: React.FC<IProps> = (props): JSX.Element => { // Render Button Type const renderButtonType = (): JSX.Element | undefined => { // Add if (props.buttonType === 'Add') { return <Icon name="ios-add" color="#FFFFFF" size={defaultStyles.fontSizeTitle1} />; } // Filter else if (props.buttonType === 'Filter') { return <Icon name="ios-filter" color="#FFFFFF" size={defaultStyles.fontSizeHeading} />; } // Message else if (props.buttonType === 'Message') { return <Icon name="ios-create-outline" color="FFFFFF" size={defaultStyles.fontSizeTitle1} />; } }; return (<TouchableOpacity style={props.darkMode ? styles.containerDark : styles.containerLight} onPress={props.onPress}><>{renderButtonType()}</></TouchableOpacity> );};
Edit: (Updated Code)
// Component: Button (Navigate)const ButtonNavigate: React.FC<IProps> = (props): JSX.Element => { // Render Icon const renderIcon = (): 'ios-add' | 'ios-filter' | 'ios-create-outline' | Error => { // Add if (props.buttonType === 'Add') { return 'ios-add'; } // Filter else if (props.buttonType === 'Filter') { return 'ios-filter'; } // Message else if (props.buttonType === 'Message') { return 'ios-create-outline'; } // Error else { throw new Error('Missing props.buttonType (Button Navigate)'); } }; return (<TouchableOpacity style={props.darkMode ? styles.containerDark : styles.containerLight} onPress={props.onPress}><Icon name={renderIcon()} color="#FFFFFF" size={defaultStyles.fontSizeTitle1} /></TouchableOpacity> );};