Viktor
Viktor

Reputation: 353

How to use <Link> tag in pure Typescript(.ts)?

So I have a function which returns me an URL

export function getUrl(params) {
  return <Link to={params}>{params.value}</Link>
}

There is no issue to use it in .tsx file, but how to adjust it for a pure Typescript(.ts)?

I'm new to Typescript and React, still learning :)

Upvotes: 3

Views: 8059

Answers (1)

mrcrowl
mrcrowl

Reputation: 1475

JSX is just syntactic sugar for function calls to React.createElement. So in theory, you could use something like:

import React, { ReactChild } from "react";
import { Link } from "react-router-dom";

export function getUrl(params: object & { value: ReactChild | ReactChild[] }) {
  return React.createElement(Link, { to: params }, params.value);
}

... but, as per the comments on your question, it's probably simpler just to use a .tsx extension.

What I suspect you're really after is the generatePath function from react-router.

Upvotes: 1

Related Questions