Highlight the text element that has been clicked

I'm looking to create a list of text elements that can be underlined when clicked individually. Adding the text decoration to the tabText applies it to all items, but I need a way to remove the underline from the previously clicked tab when clicking on a new one.

Is there a method to dynamically add or remove styles upon clicking on an item?

//onPress={() => {}}>
const tabs = [
  {
    id: 1,
    text: 'Alle List',
  },
  {
    id: 2,
    text: 'Second',
  },
];
export const Tab: React.FunctionComponent = () => {
  return (
    <View style={styles.tabView}>
      {tabs.map((item: any) => (
        <View>
          <Text style={styles.tabText}>{item.text}</Text>
        </View>
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  tabView: {
    paddingTop: moderateScale(15),
    paddingLeft: moderateScale(20),
    paddingRight: moderateScale(20),
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  tabText: {
    color: 'white',
    paddingBottom: moderateScale(10),
    //textDecorationLine: 'underline'
  },
});

Check out the Codesandbox example (with tabText items as an array too):

Answer №1

One way to enhance your script is by using useState to store the selected index and apply a different style based on that selection. Below is a modified version of your code with a link to the snack at the end for reference.

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

const tabs = [
  {
    id: 1,
    text: 'All Friends',
  },
  {
    id: 2,
    text: 'Second',
  },
  {
    id: 3,
    text: 'Third',
  },
];
export default function App() {
  const [selected, setSelected] = React.useState(null)
  return (
    <View style={styles.container}>
      <View style={styles.tabView}>
        {tabs.map((item: any, index) => (
          <TouchableOpacity onPress={()=>setSelected(index)}>
          <View>
            <Text style={[styles.tabText,selected===index?styles.selected:null]}>{item.text}</Text>
          </View>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  tabView: {
    paddingTop: 15,
    paddingLeft: 20,
    paddingRight: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  tabText: {
    color: 'black',
    paddingBottom: 10,
  },
  selected: {
    textDecorationLine: 'underline'
  },
});

Answer №2

You have the ability to customize the appearance of your tab based on the active route

<Text style={[(this.props.activeRouteName == route.routeName) ? styles.tabActiveText: styles.tabText]}>{item.text}</Text>    

Then, in the CSS:

tabActiveText: {
    color: 'white',
    paddingBottom: moderateScale(10),
    textDecorationLine: 'underline'
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating to a new state using Ionic can be done with the $state.go method within

I am experiencing an issue with Ionic routing after receiving a Push Notification. The notification contains a custom key, for example 'myKey'. When the user clicks on the notification message, it should open the application and the callback func ...

The use of a Bootstrap row is leading to incorrect dimensions for FullPageJS

Within the body tag, I have included the following code snippet: <div id="container"> <div class="section profile"> <div class="row"> <div class="col-sm-6"> A </div> ...

Tips for increasing visibility for your Google Analytics Embed API Custom Components

I recently tried to incorporate some code I found at the following link: After downloading the files view-selector2 and date-range-selector, I saved them in my local directory. I made a modification to the code: var accountSummaries = require(['&ap ...

Utilize AJAX to dynamically populate a list in CodeIgniter

Currently, I am working on a project that involves using Codeigniter. One of my tasks is to populate a dropdown list from the database using Ajax. However, I encountered an error: "Uncaught SyntaxError: missing ) after argument list." Below is the code sn ...

Save Chrome's console log programmatically

Can anyone provide insights on how to use javascript or nodejs to automatically extract the contents of Chrome's console for saving it into a file or database? ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

The added class is not being successfully applied to the ClassList

I'm currently working on a page where I want the colors of a button and the background to switch when the button is clicked. document.querySelector("body.light").classList.toggle("dark"); document.querySelector("button.dark").classList.toggle("light" ...

"Unpredictable test failures plaguing my Node.js application with jest and supertest

Recently, I've been working on developing a REST API that accepts a movie title in a POST request to the /movies route. The API then fetches information about that movie from an external API and stores it in a database. Additionally, when you make a P ...

What is the best way to transition all elements down while sliding a header up or down?

Is it possible to bring down the entire page when hovering over a header element using CSS, ensuring that the header overlaps nothing else on the page? If so, how can this be achieved? See an example of the header in action here: Thank you! ...

Leverage the power of PHP and cURL to retrieve JSON data from a file containing a mix of text, HTML

When utilizing PHP and cURL on THIS website, the returned file contains data that looks like this: <!DOCTYPE html> <html> <head></head> <body> <script> window['flyerData'] = { ...

Switching Time Display

I am trying to manipulate a time string by inserting a colon between the hour and minutes. I think using regular expressions might be the way to go, but I'm not quite sure how to implement it. Any helpful tips or suggestions would be greatly appreciat ...

Sending a request from JavaScript to C# methods using AJAX, with no expected response, within an ASP.NET MVC framework

Setting up the Environment: <package id="jQuery" version="3.2.1" targetFramework="net45" /> <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" /> Recently, I encountered an issue while trying to send a request from one ...

The body's width is more compact compared to one of my containers in HTML/CSS

After completing my code for a beginner's HTML/CSS project, I realized that the main parent container holding two smaller containers needed to be set at specific widths. The two inner containers had to be exactly 650px and 270px wide, while the main p ...

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...

Maintain consistent alignment of the backgrounds for each term-description pair within a definition list resembling a table

I am trying to style a definition list in HTML to resemble a table using th and td elements in two separate columns, while also having alternating row backgrounds. I have implemented the following CSS for this purpose: dl { font-family: Verdana, Genev ...

What is the process for generating a dynamic array in typescript?

Looking to create a TypeScript dynamic array with the desired format: const display = [ { id: 1, displayName: "Abc1" }, { id: 2, displayName: "Abc2" }, { id: 3, displayName: "Abc3" } ] Attempted the following code ...

Customizing the appearance of two separate tables

I have a pair of tables that I want to style differently. Table 1 needs the images centered with no border, while table 2 should have text left-aligned with a border. Here is the CSS: table, th, td { border: 1px solid #999; border-collapse: colla ...

Constructing a JSON schema for a dynamic aggregate query

Looking to create a query that matches fields with data in them. Here is an attempt: var matchStr = {}; if (received.user) { matchStr = { "_id": { "$regex": received.user, "$options": "i" } }; } if (received.name) { matchStr += { "name": { " ...

The React Native application is utilizing non-public selectors within the Payload

After uploading my React Native app to the app store, I encountered the following problem: The app references non-public selectors in Payload/AppGeolocNative.app/AppGeolocNative: getAuthorizationStatus:, isPassthrough, newSocketQueueForConnectionFromAddres ...

I am experiencing difficulty getting Bootstrap Columns to appear next to each other despite trying numerous solutions

Check out this code snippet: <div class="mainptext"> <h3><strong>Master the following:</strong></h3> <div class="container"> <div class="row"> <div class ...