Home > Back-end >  How to conditionally display a text as plain text and hyperlinked text in react?
How to conditionally display a text as plain text and hyperlinked text in react?

Time:11-17

I have a react component which have lets say a boolean variable isHyper based upon this i want to conditionally display a table row as hyperlink or plain row

I am able to achieve it with ternary operator or if else like this

export default function App() {
  let isHyper = true;
  return (
    <>
      {isHyper === true ? (
        <a href="www.google.com">
        <tr>
         <td>some data</td>
         <td>some data</td>
         </tr>
        </a>
      ) : (
        <tr>
         <td>some data</td>
         <td>some data</td>
         </tr>
      )}
    </>
  );
}

But here I don't want to repeat the content again and again in if else statement how can I achieve this ?

CodePudding user response:

Does this answer your question

    export default function App() {
    let isHyper = false;
    const text = "some long stuff which I don't want to repeat in else part nor I can store it as variable"
    return (
      <>
        {isHyper ? (
          <a href="www.google.com">
           {text}
          </a>
        ) : (
          <p>
            {" "}
            {text}
          </p>
        )}
      </>
    );
  }

CodePudding user response:

some long stuff which I don't want to repeat in else part nor I can store it as variable

What do you mean exactly that it can't be stored as a variable? Can you clarify this for me? Where are you getting this text from?

With React this feels like you should have a hyperlink component that can take in parameters and display it based on props. So when you call it you can pass isHyper and the text parameters into the custom component.

import React from 'react';

const HyperLink = (props) => {
  return (
    <>
      {props.isHyper && <a href="www.google.com">{props.text}</a>}
      {!props.isHyper && <div>{props.text}</div>}
    </>
  );
};
export default HyperLink;

Then where you want to call it

import HyperLink from './HyperLink';

export default function App() {
  const data = [
    { id: 1, isHyper: true, text: 'This is hyperlink text' },
    { id: 2, isHyper: false, text: 'This is not hyperlink text' },
  ];

  let display = data.map((i) => {
    return <HyperLink key={i.id} isHyper={i.isHyper} text={i.text} />;
  });

  return (
    // ...
    <div>{display}</div>
  );
}

Here is a simple working example

  • Related