How do I create a Typography component that can be used as h1, h2, h3, h4..etc

Viewed 1317

How can I create a Typography component, which can be reused with all title tags, h1, h2, h3..etc.

In the ideal world I thought of the code below, but I still haven't found in the documentation how to write it correctly.

export const Typography = (level) => styled(level)`
..style here
`;

h1:

<Typography level={h1}>Text here</Typography>

Is there any way to reproduce this?

3 Answers

Here is one complete solution that I think very closely matches your question.

Uses dynamic tag names (like other answer) and includes a styled-component that represents your Typography component. I named it StyledHeader since it really is only about the header.

A broader use would allow any tag to be sent through the same code to apply typography to any element. I'l let you expand upon this.

A working example: Demo

import React from "react";
import "./style.css";
import styled from 'styled-components'

const Header = ({tagName, ...otherProps}) =>  {
  const Tag = tagName;
  const defaultProps = {
    tagName: 'div'
  };

    return <Tag {...otherProps}/>
}


const StyledHeader = styled(Header)`
  font-style: italic;
`; 


export default function App() {
  const headers = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
  const output = headers.map(header =>
      <StyledHeader tagName={header}>Content</StyledHeader>
  );

  return (
    <div>
    {output}
    </div>
  );
}

You can try use ejs. And write code like this:

<% if(parameter == 'true'){ %>

<h1>some text</h1>

<% } %>

<% if(parameter2 == 'true'){ %>

<h2>text2</h2>

<% } %>

In js file it will look like:

render('filename.ejs',{parameter: true, parameter2: false})

I think it will work for small project, for something bigger you will need to find better solution.

if you want to use common tags you can use simple construction like this:

const styleMap={
  "h1":{
    margin: '40px',
    border: '5px solid pink'
  },
...
}
export const Typography=({Tag, children, ...otherProps})=>{
return  <Tag {...otherProps} style={styleMap[Tag]}>{children}</Tag>
}

Or variant with class styling:

import './styles.css'

const styleMap={
  h1:'h1_styled',
...
}
export const Typography = ({ Tag, children, ...otherProps }) = {
  return React.createElement(
    Tag || 'div', 
    {...otherProps, style:styleMap[Tag]}, 
    children
  );
}

For more complex tasks just consider ready-made solutions or their source code

Related