Knowledge Base (React Native Components)

Please review knowledge base, if you cannot find the answer you are looking for? Reach out to our support team by opening forum thread.

1. Mastering UX: Building Dynamic Radio Buttons React Native

 

  1. Component Structure:

    • The component is created using the React and useState from 'react' and basic UI elements like View, Text, and TouchableOpacity from 'react-native'.
    • It maintains the state of the radio button using the useState hook.
  2. Properties:

    • The component accepts several properties for customization:
      • label: The text label displayed next to the radio button.
      • enabled: A boolean indicating whether the radio button is enabled or disabled. Defaults to true.
      • buttonColor: The color of the radio button.
      • selectedButtonColor: The color of the radio button when it's selected.
      • labelColor: The color of the label text.
      • onValueChange: A callback function triggered when the radio button value changes.
  3. Event Handling:

    • The handlePress function is invoked when the TouchableOpacity is pressed.
    • It checks if the radio button is enabled before updating its state and triggering the onValueChange callback.
  4. Styling:

    • The component is styled using the StyleSheet.create method.
    • The radio button container has a row layout and margin at the bottom.
    • The actual radio button is a circle with rounded corners, and its background color changes based on its state.
  5. Usage:

    • The component is then used in a parent component, where you can customize its appearance and behavior by passing the desired properties.
    • An example usage is provided in a hypothetical app where the component is used to select options, and a callback logs the radio button value.
  6. Customization:

    • Developers can easily customize the component by adjusting the styles or extending the properties based on their specific requirements.
  7. Benefits:

    • The component provides a simple and intuitive way to integrate customizable radio buttons into React Native applications.
    • It enhances user interaction by allowing developers to control the radio button's appearance and behavior.
  8. Flexibility:

    • Developers can integrate multiple instances of the Custom RadioButton component with different configurations based on their application's needs.

 

// App.js

import React from 'react';
import { View, StyleSheet } from 'react-native';
import CustomRadioButton from './CustomRadioButton'; // Adjust the import path based on your project structure

const App = () => {
  const handleRadioButtonChange = (value) => {
    console.log('RadioButton value:', value);
  };

  return (
    <View style={styles.container}>
      <CustomRadioButton
        label="Option 1"
        enabled={true}
        buttonColor="#3498db"
        selectedButtonColor="#2ecc71"
        labelColor="#000"
        onValueChange={handleRadioButtonChange}
      />
      {/* Add more CustomRadioButton components with different configurations as needed */}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
});

export default App;

 

 

This component allows you to create customizable RadioButtons in your React Native application. You can use it by passing properties such as label, enabled, buttonColor, selectedButtonColor, labelColor, and onValueChange.

 

// CustomRadioButton.js

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

const CustomRadioButton = ({
  label,
  enabled = true,
  buttonColor = '#3498db',
  selectedButtonColor = '#2ecc71',
  labelColor = '#000',
  onValueChange,
}) => {
  const [isSelected, setSelected] = useState(false);

  const handlePress = () => {
    if (enabled) {
      const newValue = !isSelected;
      setSelected(newValue);
      onValueChange && onValueChange(newValue);
    }
  };

  return (
    <TouchableOpacity onPress={handlePress} activeOpacity={0.8} disabled={!enabled}>
      <View style={styles.radioButtonContainer}>
        <View
          style={[
            styles.radioButton,
            { backgroundColor: isSelected ? selectedButtonColor : buttonColor },
          ]}
        />
        <Text style={[styles.label, { color: labelColor }]}>{label}</Text>
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  radioButtonContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  radioButton: {
    width: 20,
    height: 20,
    borderRadius: 10,
    borderWidth: 2,
    marginRight: 5,
  },
  label: {
    fontSize: 16,
  },
});

export default CustomRadioButton;
2. Master React Native CheckBox Custom Components

step-by-step breakdown of the provided React Native Custom CheckBox component:

1. Component Structure:
     The component is created using the `React` and `useState` from 'react' and basic UI elements like `View`, `Text`, and `TouchableOpacity` from 'react-native'.
     It maintains the state of the checkbox using the `useState` hook.

2. Properties:
       The component accepts several properties for customization:
      `label`: The text label displayed next to the checkbox.
      `enabled`: A boolean indicating whether the checkbox is enabled or disabled. Defaults to `true`.
      `borderColor`: The color of the checkbox border.
      `enabledBorderColor`: The color of the checkbox border when it's enabled.
      `onValueChange`: A callback function triggered when the checkbox value changes.

3. Event Handling:
     The `handlePress` function is invoked when the TouchableOpacity is pressed.
     It checks if the checkbox is enabled before updating its state and triggering the `onValueChange` callback.

4. Styling:
     The component is styled using the `StyleSheet.create` method.
     The checkbox container has a row layout, a border, and padding.
     The actual checkbox is a square with rounded corners, and its background color changes based on its state.

5. Usage:
    The component is then used in a parent component, where you can customize its appearance and behavior by passing the desired properties.
    An example usage is provided in a hypothetical app where the component is used to enable or disable a feature, and a callback logs the checkbox value.

6. Customization:
    Developers can easily customize the component by adjusting the styles or extending the properties based on their specific requirements.

7. Benefits:
   The component provides a simple and intuitive way to integrate customizable checkboxes into React Native applications.
   It enhances user interaction by allowing developers to control the checkbox's appearance and behavior.

8. Flexibility:
   Developers can integrate multiple instances of the Custom CheckBox component with different configurations based on their application's needs.

By following these steps, you can integrate this Custom CheckBox component into your React Native application, providing a flexible and user-friendly checkbox solution.

 

// App.js

import React from 'react';
import { View, StyleSheet } from 'react-native';
import CustomCheckBox from './CustomCheckBox'; // Adjust the import path based on your project structure

const App = () => {
  const handleCheckBoxChange = (value) => {
    console.log('CheckBox value:', value);
  };

  return (
    <View style={styles.container}>
      <CustomCheckBox
        label="Enable Feature"
        enabled={true}
        borderColor="#333"
        enabledBorderColor="#00f"
        onValueChange={handleCheckBoxChange}
      />
      {/* Add more CustomCheckBox components with different configurations as needed */}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
});

export default App;

 

 

You can use this component in your React Native application and pass the desired properties like label, enabled, borderColor, enabledBorderColor, and onValueChange to customize its behavior and appearance.

 

// CustomCheckBox.js

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

const CustomCheckBox = ({
  label,
  enabled = true,
  borderColor = '#000',
  enabledBorderColor = '#00f',
  onValueChange,
}) => {
  const [isChecked, setChecked] = useState(false);

  const handlePress = () => {
    if (enabled) {
      const newValue = !isChecked;
      setChecked(newValue);
      onValueChange && onValueChange(newValue);
    }
  };

  return (
    <TouchableOpacity onPress={handlePress} activeOpacity={0.8} disabled={!enabled}>
      <View style={[styles.checkboxContainer, { borderColor: enabled ? enabledBorderColor : borderColor }]}>
        <View style={[styles.checkbox, { backgroundColor: isChecked ? enabledBorderColor : 'transparent' }]} />
        <Text style={styles.label}>{label}</Text>
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
    borderWidth: 2,
    borderRadius: 5,
    padding: 5,
  },
  checkbox: {
    width: 20,
    height: 20,
    borderRadius: 3,
    borderWidth: 2,
    marginRight: 5,
  },
  label: {
    fontSize: 16,
  },
});

export default CustomCheckBox;
3. React Native Custom Simple TextInput Component

This CustomTextInput component takes the following props:

  • type: Specifies the input type ('text', 'number', 'password').
  • keyboardType: Specifies the keyboard type ('default', 'numeric', 'email-address', etc.).
  • editable: Determines if the input is editable or not.
  • placeholder: Placeholder text for the input.
  • value: The current value of the input.
  • onChangeText: Callback function triggered when the text changes.
  • secureTextEntry: If type is 'password', it sets the secureTextEntry prop to true.
  • style: Additional styles for customization.

You can use this component in your application like this:

 

// App.js

import React, { useState } from 'react';
import { View, Text } from 'react-native';
import CustomTextInput from './CustomTextInput';

const App = () => {
  const [text, setText] = useState('');

  return (
    <View>
      <Text>Custom TextInput Example:</Text>

      <CustomTextInput
        type="text"
        keyboardType="default"
        editable={true}
        placeholder="Enter text"
        value={text}
        onChangeText={(newText) => setText(newText)}
        style={{ marginBottom: 20 }}
      />

      <CustomTextInput
        type="number"
        keyboardType="numeric"
        editable={true}
        placeholder="Enter number"
        value={text}
        onChangeText={(newText) => setText(newText)}
        style={{ marginBottom: 20 }}
      />

      <CustomTextInput
        type="password"
        keyboardType="default"
        editable={true}
        placeholder="Enter password"
        value={text}
        onChangeText={(newText) => setText(newText)}
        style={{ marginBottom: 20 }}
      />
    </View>
  );
};

export default App;

 

The CustomTextInput component uses the TextInput component from React Native and applies styles defined in the styles object. The default styles include a height, border color, border width, padding, and margin, providing a basic and consistent look for the text input. This customizable text input component is useful for creating a variety of input fields within a React Native application.

 

// CustomTextInput.js

import React from 'react';
import { TextInput, StyleSheet } from 'react-native';

const CustomTextInput = ({
  type = 'text', // 'text', 'number', 'password'
  keyboardType = 'default', // 'default', 'numeric', 'email-address', etc.
  editable = true,
  placeholder = 'Enter text',
  value,
  onChangeText,
  secureTextEntry = false,
  style,
}) => {
  return (
    <TextInput
      style={[styles.input, style]}
      keyboardType={keyboardType}
      placeholder={placeholder}
      value={value}
      onChangeText={onChangeText}
      secureTextEntry={type === 'password' ? true : secureTextEntry}
      editable={editable}
    />
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    padding: 10,
    marginVertical: 10,
  },
});

export default CustomTextInput;
4. React Native Custom Card Component

STEP :1

This code defines a simple React Native app using a custom card component called CustomCard. The app renders a single CustomCard with customized styles and content, such as background color, border color, and labels for the header, body, and footer. The CustomCard component is likely defined in a separate file and receives these customization details through props. The app can be expanded by adding more instances of the CustomCard component inside the main <View>. Each card can have its own unique styles and content, making it a flexible and reusable component for displaying information in a mobile app.

 

// App.js

import React from 'react';
import { View } from 'react-native';
import CustomCard from './CustomCard';

const App = () => {
  return (
    <View>
      <CustomCard
        style={{ marginBottom: 20 }}
        borderColor="blue"
        bgColor="lightblue"
        color="black"
        borderRadius={12}
        height={150}
        width={300}
        showHeader={true}
        headerLabel="Custom Card Header"
        showBody={true}
        bodyLabel="This is the body of the card."
        showFooter={true}
        footerLabel="Custom Card Footer"
      />

      {/* Add more CustomCard components as needed */}
    </View>
  );
};

export default App;



STEP :2

This code defines a reusable CustomCard component in React Native. The component takes various props to customize its appearance, including border color, background color, text color, border radius, dimensions, and content visibility. The card is structured with optional header, body, and footer sections, each displaying text content. The styles are defined using the StyleSheet module to ensure consistent and easily maintainable styling. The default values for props are set to create a clean and simple card if no customization is provided. This CustomCard component serves as a modular and flexible way to display information in a styled card format, and it can be easily integrated and customized within a React Native application.

 

// CustomCard.js

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

const CustomCard = ({
  style,
  borderColor = 'black',
  bgColor = 'white',
  color = 'black',
  borderRadius = 8,
  height,
  width,
  showHeader = true,
  headerLabel = 'Header',
  showBody = true,
  bodyLabel = 'Body',
  showFooter = true,
  footerLabel = 'Footer',
}) => {
  return (
    <View style={[styles.card, { borderColor, backgroundColor: bgColor, color, borderRadius, height, width }, style]}>
      {showHeader && (
        <View style={styles.header}>
          <Text style={styles.headerText}>{headerLabel}</Text>
        </View>
      )}

      {showBody && (
        <View style={styles.body}>
          <Text style={styles.bodyText}>{bodyLabel}</Text>
        </View>
      )}

      {showFooter && (
        <View style={styles.footer}>
          <Text style={styles.footerText}>{footerLabel}</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  card: {
    borderWidth: 1,
    padding: 10,
    marginBottom: 10,
  },
  header: {
    borderBottomWidth: 1,
    paddingBottom: 5,
    marginBottom: 5,
  },
  headerText: {
    fontWeight: 'bold',
  },
  body: {
    marginBottom: 5,
  },
  bodyText: {},
  footer: {
    borderTopWidth: 1,
    paddingTop: 5,
    marginTop: 5,
  },
  footerText: {
    fontStyle: 'italic',
  },
});

export default CustomCard;
5. React Native Custom Button Component

Create a new React Native project or use an existing one:

npx react-native init YourProjectName

 

Navigate to your project directory:

cd YourProjectName

 

Create a new file for your button component:

touch CustomButton.js

 

CustomButton component with additional properties such as disabled, rounded, and icon:

// CustomButton.js

import React from 'react';
import { TouchableOpacity, Text, StyleSheet, View } from 'react-native';
import { FontAwesome } from '@expo/vector-icons'; // Assuming you have FontAwesome installed

const CustomButton = (props) => {
  const {
    onPress,
    title,
    color,
    style,
    disabled,
    rounded,
    icon,
    iconPosition,
    iconColor,
    iconSize,
  } = props;

  const renderIcon = () => {
    if (icon) {
      const iconComponent = <FontAwesome name={icon} size={iconSize} color={iconColor} />;
      return iconPosition === 'left' ? (
        <View style={styles.iconLeft}>{iconComponent}</View>
      ) : (
        <View style={styles.iconRight}>{iconComponent}</View>
      );
    }
    return null;
  };

  return (
    <TouchableOpacity
      onPress={onPress}
      style={[
        styles.button,
        { backgroundColor: color },
        rounded && styles.roundedButton,
        disabled && styles.disabledButton,
        style,
      ]}
      disabled={disabled}
    >
      {iconPosition === 'left' && renderIcon()}
      <Text style={styles.buttonText}>{title}</Text>
      {iconPosition === 'right' && renderIcon()}
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    padding: 10,
    borderRadius: 5,
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 10,
    flexDirection: 'row',
  },
  roundedButton: {
    borderRadius: 25,
  },
  disabledButton: {
    opacity: 0.7,
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    marginLeft: 8, // Adjust the spacing between text and icon
    marginRight: 8,
  },
  iconLeft: {
    marginRight: 8,
  },
  iconRight: {
    marginLeft: 8,
  },
});

export default CustomButton;

 

Using the custom button in your main component:

// App.js

import React from 'react';
import { View, Alert } from 'react-native';
import CustomButton from './CustomButton';

const App = () => {
  const handleButtonPress = () => {
    Alert.alert('Button Pressed');
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <CustomButton
            onPress={handleButtonPress}
            title="Press Me"
            color="green"
            style={{ width: 200 }}
            disabled={false} // Set to true to disable the button
            rounded={true} // Set to true for a rounded button
            icon="rocket" // Icon name from FontAwesome
            iconPosition="left" // or "right"
            iconColor="white"
            iconSize={20}
       />
    </View>
  );
};

export default App;