Home > Back-end >  ReactJS - How do show multiple clickable links in a table cell when data has text multiple links?
ReactJS - How do show multiple clickable links in a table cell when data has text multiple links?

Time:11-05

I have an app with back-end database data displayed in a ReactJS front end app. The data is displayed in a HTML table (rows and columns). One of the columns has text as below:

"One http://www.example_1.com/    Two http://www.example_2.com/"

This text can have one link or two or three. When I display it in the table cell I want these links to show as clickable hyper links. This is the issue I am trying.

When a column has one link text only , I can code like this in react program. This shows as clickable hyperlink in a table cell (works fine):

<td><a href={row.link_text}>{row.link_text}</a></td>

When I have text with one link like "Some txt and http://www.example.com/", I can convert the text into two sub strings - one with text and one with link text - and show the data in a cell using (works fine):

<td>{row.text_without_link}<a href={row.link_text}>{row.link_text}</a></td>

How do I make the hyperlinks dynamically when the text has multiple links text (one or more)?

Is there is standard way (technique) for this or do I have to write lot of code for this in the reactjs program?

I welcome any help and suggestions to solve this. Thank you.


The React component class's render method looks like this (the table is formatted using HTML and CSS):

render() {
    const tableRows = this.props.data.map((row, i) =>
        <tr key={i} >
            <td>{row.some_column}</td>
            <td>{row.text_without_link}<a href={row.link_text}>{row.link_text}</a></td>
        </tr>
    );
    return 
        <table>
            <thead>...</thead>
            <tbody>
                {tableRows}
            </tbody>
...

CodePudding user response:

render() {
const URL_REGEX =
/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9] ([\-\.]{1}[a-z0-9] )*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;

function Text({ content }) {
const words = content.split(' ');
return (
    <p>
        {words.map((word) => {
            return word.match(URL_REGEX) ? (
                <>
                    <a href={word}>{word}</a>{' '}
                </>
            ) : (
                word   ' '
            );
        })}
    </p>
);
}


const tableRows = this.props.data.map((row, i) =>
    <tr key={i} >
        <td>{row.some_column}</td>
        <td>{<Text content={row.column_text}/>}</td>
    </tr>
);
return 
    <table>
        <thead>...</thead>
        <tbody>
            {tableRows}
        </tbody>
  • Related