简体   繁体   中英

React's Python-like formatted string

In Python you can do such a thing:

string_to_format = "Hey {name}"
formatted_string = string_to_format.format(name="John")
print(formatted_string)

The result would be:

Hey John

I want to do the same in React. I know about f-strings in Python and their equivalent in ES6, but this is not the case, because f-strings need the variable that is put to string to be defined. My use case is this:

  • pass a string like /user/{userName}/details to a component
  • component creates a table in which every row is clickable ( <Link to={...} /> ) and the path is determined by a value in some row's column

So for example for a row like:

foo 1234

The path would be: /user/foo/details . You can see the pattern.

So as I mentioned, I cannot format the string before passing it to a component because it has to be formatted deep in this child component's render function, like in a map statement.

Is there a way to do it in React?

PS I use TypeScript

@Edit:

This is what I really wanna do:

I have a generic PaginatedTable component. It takes columns and rows lists + a configuration as props.

The configuration is as follows:

interface RowClickConfig {
  rowKey: string;
  to: string;
}

So now, to is put in Link ( import { Link } from "react-router-dom"; , so from react-router-dom , not a MUI one, or something like this). And normally, if I would have one table, then I wouldn't have to do this, because to could be specified where I actually have a variable I want to put in it like /user/${userName}/details . But since it's a generic table, those to values would differ, because one table will have users, and each row click would go to a different page with a different user, but if I want to reuse this table for, I don't know, items, then the to would be /items/${itemId} or something like this.

So when I create this config prop and pass it to my table component, I don't have a definition for a variable that will be put to to field. I want it to be a placeholder, like in Python, so I can later swap it with something like .format(userName="foo") .

You can import generatePath from react-router-dom and do something very close.

import { generatePath } from "react-router";

...

const pathTemplate = "/user/:userName/details";

...

const path = generatePath(pathTemplate, { userName: 'Drew' }); // "/user/Drew/details"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM