How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into

<a href="Some Link"> Some Text </a>

Both the "Some Text" and "Some Link" values are sourced from variables.

I have managed to fetch the "Some Text" from a variable

<dd><a href="{thisDoesNotWork}">{someText}</a></dd>

However, I am struggling to make the href attribute work with a variable string as it is being taken literally. How can I make the href work with a variable string?

Providing more context:

Current typescript code:

return (
   <div>
      ....
      <dd><a href="hardCodedSomething">{someText}</a></dd>
   </div>
)

Desired behavior:

var someDynamicUrl = "somepath.com" + someId

return (
   <div>
      ....
      <dd><a href="someDynamicUrl">{someText}</a></dd>
   </div>
)

Answer №1

It seems like your current issue is more tied to react rather than typescript.

You're on the right track to getting it to work:

  • val needs to be changed to var
  • The value of the href attribute should be enclosed in curly brackets as well

Below is the updated code snippet:

var dynamicUrl = "somepath.com/" + someId;
var text = "your text";

return (
   <div>
      ....
      <dd><a href={dynamicUrl}>{text}</a></dd>
   </div>
);

Answer №2

Try using 'string' instead of 'String' if you are encountering issues. For more information, check out this link: Understanding the distinction between types String and string

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

Angular Custom Pipe - Grouping by Substrings of Strings

In my Angular project, I developed a custom pipe that allows for grouping an array of objects based on a specific property: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'groupBy'}) export class GroupByPipe impleme ...

Transform string enum type into a union type comprising enum values

Is there a way to obtain a union type from a typescript string enum? enum MyEnum { A = 'a', // The values are different from the keys, so keyof will not provide a solution. B = 'b', } When working with an enum type like the one sh ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

Ajax: The function assigned to the route does not get executed

Pressing a button triggers a confirmation box. If 'ok' is clicked, the div called 'EventData' should display the word 'reached'. The confirmation box appears when the button is clicked, but 'EventData' does not show ...

Ways to stop your Browser from Caching

Developing a Facebook app has been my recent project. One thing that really bothers me is the random occurrences where changes I make to my CSS style sheet or when adding a new Javascript function do not reflect in the browser. This can be very frustrating ...

Decide on the return type of a generic function depending on the parameters of the function

I have a series of TypeScript functions that are structured as follows: useCustomFunction = <T>(key: CustomType) : T => { // implementation details here } The parameter type is restricted to a specific set of strings: type CustomType = "apple ...

When coding in JavaScript, the value of "this" becomes undefined within a class function

I'm facing an issue with my TypeScript class that contains all my Express page functions. When I try to access the class member variable using this, I get an 'undefined' error: class CPages { private Version: string; constructor(ver ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

Typescript Error:TS2345: The argument '{ theme: string; jsonFile: string; output: string; }; }' is not compatible with the parameter type 'Options'

Encountering an error mentioned in the title while using the code snippet below: import * as fs from 'fs' import { mkdirp } from 'mkdirp' import * as report from 'cucumber-html-reporter' const Cucumber = require('cucumber ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

emphasizing the specific text being searched for within the page

Looking for a solution to search values and highlight matching text words on a page? Let me help you with that. $(function() { var tabLinks = $('.nav > li'), tabsContent = $('.tab-content > div'), ...

A dynamically-generated dropdown element in the DOM is being duplicated due to JavaScript manipulation

Currently, I am dynamically adding a dropdown element to the page using javascript. The goal is for this dropdown to modify the properties displayed on a map. However, when attempting to add the element after the map loads, I encounter an issue where the d ...

What's the most effective method to incorporate additional events into this element using the conditional operator?

Looking for help with this code snippet: <span role="link" tabindex="0" :class="tabDetails.showPayment ? 'link' : ''" @click="tabDetails.showPayment ? cTab('payments') : null" ...

Utilize Jquery to hide radio buttons, while allowing users to click on an image to display a larger version

My current HTML structure is restricted to SAAS, so I only have control over jQuery implementation. https://i.stack.imgur.com/OHB9K.jpg I am attempting to achieve a similar layout as shown in the image below. The main issue lies in how to (1) conceal ...

Is there a way to prevent the Pace js plugin from running on page load, but still have it execute during Ajax requests only?

I have successfully implemented the jquery pace plugin with a progress bar theme. Everything is working well, but I am looking to make it run only on ajax requests. I have tried various solutions found through research, but haven't had any luck. Belo ...

Interact with a modal element using puppeteer

I'm having trouble clicking on the email login button inside a modal using Puppeteer for automation. The code is not able to find the modal element. Can someone assist me in debugging this issue? const puppeteer = require('puppeteer'); ( ...

Writing TypeScript, Vue, and playing around with experimental decorators

After creating a Vue project through Vue-CLI v3.0.0-beta.15, the project runs smoothly when using npm run serve. However, TypeScript displays an error message stating that support for decorators is experimental and subject to change in a future release, bu ...

Customizing the layout of specific pages in NextJSIncorporating

In my Next.js project, I'm trying to set up a header and footer on every page except for the Login page. I initially created a layout.tsx file in the app directory to apply the layout to all pages, which worked fine. However, when I placed another lay ...

Trouble occurs in the HTML code when trying to access a property from an inherited interface in Angular

Currently, I am working with Angular 17 and have encountered a specific query: In my project, there is an IDetails interface containing certain properties: export interface IDetails { summary: Summary; description: string; } Additionally, there is an ...

Why are static PropTypes used in ReactJS and do they offer any solutions or are they merely a recurring design choice?

While delving into the code base of a web application, I came across some static PropTypes that left me questioning their purpose and necessity. Here is a snippet of the code in question: static propTypes = { fetchCricketFantasyPlayers: PropTypes.fun ...