skip to Main Content

I am having array of data which I am maping using .map method. How can I remove duplicate code i.e.

<a href={usp.url}>
   <div>{usp.text}</div>
</a>

Code can be found on code sandbox https://codesandbox.io/s/modern-haze-b9016d?file=/src/App.tsx

2

Answers


  1. Do you mean creating a component like this?

    You can put your link into another component, e.g.: MyLink and export it from the file.

    MyLink.tsx :

    type MyLinkProp = {
      url: string;
      text: string;
    };
    const MyLink = (props: MyLinkProp) => {
      return (
        <a href={props.url}>
          <div>{props.text}</div>
        </a>
      );
    };
    
    export default MyLink;
    
    

    Then in your App.tsx, replace <a>...</a> with <MyLink/> and add the required properties to it:

    <MyLink url={usp.url} text={usp.text} />
    
    Login or Signup to reply.
  2. You can use

    !!["desktop", "mobile", "both"].includes(usp.display) && (
        <a href={usp.url}>
            <div>{usp.text}</div>
        a>
    )
    

    Note: I see that you are using a map without key, you should always use unique keys when iterating over a list.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search