Home > other >  How to pass in tags such as [<h1/><h2/>..] as parameters to be able to build a new compo
How to pass in tags such as [<h1/><h2/>..] as parameters to be able to build a new compo

Time:10-26

I want to be able to pass header tags as parameters to build a custom component that changes size. Here is code for more context on what I am trying to acheive

const Course =({course})=>{
    return(
      <div>
        <Header text={"Web dev cirriculum"} size ={"h1"}/>
        <Header text={course.name} size={"h2"}/>
        <Content course ={course}/>
      </div>     
    )
  }

const Header = ({text,size}) => {
  return (
    {<{size}>{text}</{size}>}
  )
}

As you can see above I am trying to pass in a string "h1" and "h2" on my <Header/> component to build custom sized headers.

CodePudding user response:

Change header to this:

const Header = ({ text, size }) => {
  const Component = size;
  return (
    <Component>{text}</Component>
  )
}

The renaming is just there because the JSX requires us to use a capital letter. If you change the prop to start with a capital letter, then you can use it directly:

const Header = ({ text, Size }) => {
  return (
    <Size>{text}</Size>
  )
}
  • Related