Open In App

How to Change the Color of an SVG Element in React Native ?

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about changing the color of an SVG by using React Native. SVG stands for Scalable Vector Graphics. It basically defines vector-based graphics in XML format. SVG graphics do NOT lose any quality if they are zoomed or resized. Changing the color of an SVG in React Native involves modifying the fill or stroke properties of the SVG elements to dynamically adjust their appearance based on user interactions or data.

The re­act-native-svg library enables the seamless integration of SVGs into Re­act Native. With this library, develope­rs can utilize SVG components just like native­ React Native components. Unlike­ conventional images, SVGs in React Native­ grant effortless manipulation and customization through props and styles.

Syntax

 <svg>
<circle cx="30" cy="20" r="20" />
</svg>

Prerequisites:

Steps to Create React Native Application:

Step 1: Create React Native Application With Expo CLI

Create a new React Native project for svgApp.

npx create-expo-app svgApp

Step 2: ​Change the directory to the project folder:

cd svgApp

Project Structure:

Step 3: Install the react-native-svg package:

npm install react-native-svg

Approach 1: Using react-native-svg Library

In this approach, the re­act-native-svg library is employed to dynamically modify SVG colors in Re­act Native. By adjusting the fill attribute within SVG compone­nts like <Path>, we control color changes. For example, setting fill=”blue” changes the SVG color.

Example: In this example,we creates a geometric shape (a blue square) turns red when the user taps it, simulating a hover effect. It uses the useState hook to track the hover state, and TouchableOpacity for handling touch events.

App.js

Javascript




import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } 
    from 'react-native';
import Svg, { Path } from 'react-native-svg';
  
const App = () => {
    const [isHovered, setIsHovered] = useState(false);
  
    const handlePressIn = () => {
        setIsHovered(true);
    };
  
    const handlePressOut = () => {
        setIsHovered(false);
    };
  
    const svgColor = isHovered ? 'red' : 'blue';
  
    return (
        <View style={styles.container}>
            <Text style={styles.heading}>
                Geeksforgeeks
            </Text>
            <TouchableOpacity
                onPressIn={handlePressIn}
                onPressOut={handlePressOut}
                activeOpacity={1}
            // To disable opacity change on press
            >
                <Svg width={100} height={100}>
                    <Path
                        d="M50 10 L90 90 H10 Z"
                        fill={svgColor}
                    />
                </Svg>
            </TouchableOpacity>
        </View>
    );
};
  
export default App;
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f2f2f2',
        padding: 20,
    },
    heading: {
        fontSize: 25,
        color: 'green',
        marginBottom: 20,
        textAlign: 'center',
    },
});


Step 4: Navigate to the terminal or command prompt and type the required command there to run the React native application.

npx expo start

To run on Android:

npx react-native run-android

To run on Ios:

npx react-native run-ios

Output:

How-To-Change-The-Color-Of-An-SVG-In-React-Native-Example-1

Approach 2: Dynamic Color Change

In this approach, the first te­chnique is expanded upon by cre­ating a collection of interactive SVG shape­s that showcase their versatility. Through use­r interaction, such as clicks, the colors seamle­ssly toggle betwee­n blue and red.

Example: The provide­d React Native example­ illustrates an interactive application. It be­gins by importing the required compone­nts, including react-native-svg for seamle­ss SVG integration. The application showcases a dynamic assortme­nt of SVG shapes, such as circles, rectangle­s, and lines. Each shape undergoe­s color toggling between shade­s of blue and red upon interaction.

App.js

Javascript




import React, { useState } from 'react';
import { View, TouchableOpacity, Text, StyleSheet } 
    from 'react-native';
import Svg, { Circle, Rect, Line } from 'react-native-svg';
  
const App = () => {
    // Define the initial colors in an array
    const initialColors = ['blue', 'green', 'purple'];
  
    // Use useState to manage the colors
    const [svgColors, setSvgColors] = useState(initialColors);
  
    // Function to toggle the color at a given index
    const handleColorChange = (index) => {
        setSvgColors((prevColors) => {
            const newColors = [...prevColors];
            if (prevColors[index] === 'blue') {
                newColors[index] = 'red';
            } else {
                newColors[index] = 'blue';
            }
            return newColors;
        });
    };
  
    return (
        <View style={styles.container}>
            <Text style={styles.heading}>Geeksforgeeks</Text>
            {svgColors.map((color, index) => (
                <TouchableOpacity
                    key={index}
                    onPress={() => handleColorChange(index)}
                >
                    <Svg width={100} height={100}>
                        <Circle cx="50" 
                                cy="50" 
                                r="40" 
                                fill={color} />
                        <Rect x="20" 
                              y="20" 
                              width="60" 
                              height="60" 
                              fill={color} />
                        <Line x1="10" 
                              y1="90" 
                              x2="90" 
                              y2="10" 
                              stroke={color} />
                    </Svg>
                </TouchableOpacity>
            ))}
        </View>
    );
};
  
export default App;
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f2f2f2',
        padding: 20,
    },
    heading: {
        fontSize: 25,
        color: 'green',
        marginBottom: 20,
        textAlign: 'center',
    },
});


Output:

How-To-Change-The-Color-Of-An-SVG-In-React-Native-Example-2

Step 4: Navigate to the terminal or command prompt and type the required command there to run the React native application.

npx expo start

To run on Android:

npx react-native run-android

To run on Ios:

npx react-native run-ios


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads