Create Focusable Button
Since we will need to add 2 buttons to the VideoDetailScreen that can be focused, we will create our own button component. This also ensures that we are not duplicating code and the button can be re-used across our App.
Define Button component
- Create a new file under the components folder called
Button.tsx. - Import React and useState from 'react'.
- Import StyleSheet, Text and TouchableOpacity from 'react-native'.
- Create an arrow function called Button that takes in 2 arguments called
pressFunctionandbuttonText. - Destructure each argument in the interface and add
:IPropsto enforce the type of each argument in the object. ThepressFunctionwill be a Function and thebuttonTexta string. - Below the import statements, create an interface that declares the types of the props.
import React, { useState } from 'react';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
export interface IProps {
pressFunction: Function;
buttonText: String;
}
const Button = ({ pressFunction, buttonText }: IProps) => { };
- Add an empty fragment and inside it add a TouchableOpacity element.
To make the Button pressable we need to give it an onPress().
- Add the onPress prop to TouchableOpacity and set its value to call the pressFunction
- Add a Text component inside the TouchableOpacity and set it to take in the value of buttonText.
const Button = ({ pressFunction, buttonText }: IProps) => {
return (
<>
<TouchableOpacity onPress={() => pressFunction()}>
<Text>{buttonText}</Text>
</TouchableOpacity>
</>
);
};
Next we want to make it obvious to the user that the button has been selected, so let's add onFocus() and onBlur() properties to the TouchableOpacity
- Import
useStatefrom react and initialize it with a state offocusedand a function ofsetFocused. - Initialize the value of
focusedto false.
const Button = ({ pressFunction, buttonText }: IProps) => {
const [focused, setFocused] = useState(false);
}
- Add an
onFocusprop to the TouchableOpacity, and set it to call thesetFocused()function with the valuetrue - Add an
onBlurprop to the TouchableOpacity, and set it to call thesetFocused()function with the valuefalse
Your Button.tsx code should look like this:
Add Styling
Now let's add some styling:
- Create a StyleSheet called styles and add it after the Button function.
- Add
buttonContainer,buttonTextandfocusedstyles to the StyleSheet with the following values:
The TouchableOpacity will have a style prop that depends on the value of focused:
- Give the touchable opacity a style prop of buttonInnerContainer and a conditional style prop of focused
style={[styles.buttonInnerContainer, focus && styles.focused]} - Add the buttonOuterContainer style to the View component.
The final Button.tsx code should look like this:

