Home > Software engineering >  How to import component as a button in Nextjs?
How to import component as a button in Nextjs?

Time:04-22

I have this component with an internal link which is used in multiple pages

component

when I try to import it as a button in the Nextjs application I get this result, it renders both the styled anchor link and the button in the background

enter image description here

enter image description here

With the exact same code in the React application I get the desired result enter image description here

It looks like the prop "as" for some reason is rendering the component as a button and also the anchor inside the component, which is not happening in the regular React version

CodePudding user response:

I suspect you have different styling in "the regular React version".

Your component will always render <a> because that's hardcoded. If you want to use <a> as a default component to render, you can define a default value for as property and you don't need nested <a>.

For example:

const Comp=({as: Component = 'a', ...rest}) => {
 return <Component {...rest}>Foobar</Component>
}

then following usage will render <a> and <button>:

      <Comp />
      <Comp as="button" />

enter image description here

  • Related