React Styled component: how to add css styles based on props?












0















I've been trying to find the solution to my problem.
I have several Heading Tags (H1, H2 etc) each in their own file.
I would like to add some css when calling them based on a prop. Some headings have a small border-bottom and some don't. So, in order to refractor my code, I want to add some css based on a prop. I can't seem to find a way.



Here's an example of Heading H2:



import styled from 'styled-components';
import colors from '../../../../colors';
import fonts from '../../../../fonts';
import fontWeights from '../../../../fontWeights';

const HeadingH2 = styled.h2`
color: ${colors.text};
font-family: ${fonts.montSerrat};
font-size: 1.6em;
font-weight: ${fontWeights.light};
letter-spacing: 0.2em;
padding-bottom: 0.7em;
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
`;

export default HeadingH2


Example of calling Heading H2:



import React from 'react';
import HeadingH2 from '../../common/headings/heading_h2';
import HeadingBaseline from '../../common/headings_baseline';


// Features
import {SectionContainer, FeaturesContainer} from './features.style';

import Feature from './feature';
import feature1 from '../../../img/features/feature1.png';
import feature2 from '../../../img/features/feature2.png';
import feature3 from '../../../img/features/feature3.png';

// Text
import Text from '../../../content';

const Features = () => {
return(
<SectionContainer id={"what"}>
<HeadingH2>
What We Do
</HeadingH2>
<HeadingBaseline>
{Text.headingBaseline}
</HeadingBaseline>
<FeaturesContainer>
<Feature
src={feature1}
headingText={Text.feature1.heading}
paragraph={Text.feature1.paragraph}
/>
<Feature
src={feature2}
headingText={Text.feature2.heading}
paragraph={Text.feature2.paragraph}
/>
<Feature
src={feature3}
headingText={Text.feature3.heading}
paragraph={Text.feature3.paragraph}
/>
</FeaturesContainer>
</SectionContainer>
)
};

export default Features;


I want to extract the following CSS properties



position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);


So, assuming I have the above CSS rule in a separate file, how do I add/import them using props on my styled component HeadingH2.



Thanks for the help :)










share|improve this question

























  • I've never used styled-components but there appears to be an example of what you want to do on the library's homepage. Essentially the styled component has access to props when building the CSS string and you could overwrite/add styles based on them.

    – numbers1311407
    Dec 31 '18 at 14:55













  • not quite. I need to be able to add css rules whenever I want and from a specific file. The example on the homapage is not modular at all.

    – allan00958
    Dec 31 '18 at 16:48
















0















I've been trying to find the solution to my problem.
I have several Heading Tags (H1, H2 etc) each in their own file.
I would like to add some css when calling them based on a prop. Some headings have a small border-bottom and some don't. So, in order to refractor my code, I want to add some css based on a prop. I can't seem to find a way.



Here's an example of Heading H2:



import styled from 'styled-components';
import colors from '../../../../colors';
import fonts from '../../../../fonts';
import fontWeights from '../../../../fontWeights';

const HeadingH2 = styled.h2`
color: ${colors.text};
font-family: ${fonts.montSerrat};
font-size: 1.6em;
font-weight: ${fontWeights.light};
letter-spacing: 0.2em;
padding-bottom: 0.7em;
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
`;

export default HeadingH2


Example of calling Heading H2:



import React from 'react';
import HeadingH2 from '../../common/headings/heading_h2';
import HeadingBaseline from '../../common/headings_baseline';


// Features
import {SectionContainer, FeaturesContainer} from './features.style';

import Feature from './feature';
import feature1 from '../../../img/features/feature1.png';
import feature2 from '../../../img/features/feature2.png';
import feature3 from '../../../img/features/feature3.png';

// Text
import Text from '../../../content';

const Features = () => {
return(
<SectionContainer id={"what"}>
<HeadingH2>
What We Do
</HeadingH2>
<HeadingBaseline>
{Text.headingBaseline}
</HeadingBaseline>
<FeaturesContainer>
<Feature
src={feature1}
headingText={Text.feature1.heading}
paragraph={Text.feature1.paragraph}
/>
<Feature
src={feature2}
headingText={Text.feature2.heading}
paragraph={Text.feature2.paragraph}
/>
<Feature
src={feature3}
headingText={Text.feature3.heading}
paragraph={Text.feature3.paragraph}
/>
</FeaturesContainer>
</SectionContainer>
)
};

export default Features;


I want to extract the following CSS properties



position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);


So, assuming I have the above CSS rule in a separate file, how do I add/import them using props on my styled component HeadingH2.



Thanks for the help :)










share|improve this question

























  • I've never used styled-components but there appears to be an example of what you want to do on the library's homepage. Essentially the styled component has access to props when building the CSS string and you could overwrite/add styles based on them.

    – numbers1311407
    Dec 31 '18 at 14:55













  • not quite. I need to be able to add css rules whenever I want and from a specific file. The example on the homapage is not modular at all.

    – allan00958
    Dec 31 '18 at 16:48














0












0








0








I've been trying to find the solution to my problem.
I have several Heading Tags (H1, H2 etc) each in their own file.
I would like to add some css when calling them based on a prop. Some headings have a small border-bottom and some don't. So, in order to refractor my code, I want to add some css based on a prop. I can't seem to find a way.



Here's an example of Heading H2:



import styled from 'styled-components';
import colors from '../../../../colors';
import fonts from '../../../../fonts';
import fontWeights from '../../../../fontWeights';

const HeadingH2 = styled.h2`
color: ${colors.text};
font-family: ${fonts.montSerrat};
font-size: 1.6em;
font-weight: ${fontWeights.light};
letter-spacing: 0.2em;
padding-bottom: 0.7em;
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
`;

export default HeadingH2


Example of calling Heading H2:



import React from 'react';
import HeadingH2 from '../../common/headings/heading_h2';
import HeadingBaseline from '../../common/headings_baseline';


// Features
import {SectionContainer, FeaturesContainer} from './features.style';

import Feature from './feature';
import feature1 from '../../../img/features/feature1.png';
import feature2 from '../../../img/features/feature2.png';
import feature3 from '../../../img/features/feature3.png';

// Text
import Text from '../../../content';

const Features = () => {
return(
<SectionContainer id={"what"}>
<HeadingH2>
What We Do
</HeadingH2>
<HeadingBaseline>
{Text.headingBaseline}
</HeadingBaseline>
<FeaturesContainer>
<Feature
src={feature1}
headingText={Text.feature1.heading}
paragraph={Text.feature1.paragraph}
/>
<Feature
src={feature2}
headingText={Text.feature2.heading}
paragraph={Text.feature2.paragraph}
/>
<Feature
src={feature3}
headingText={Text.feature3.heading}
paragraph={Text.feature3.paragraph}
/>
</FeaturesContainer>
</SectionContainer>
)
};

export default Features;


I want to extract the following CSS properties



position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);


So, assuming I have the above CSS rule in a separate file, how do I add/import them using props on my styled component HeadingH2.



Thanks for the help :)










share|improve this question
















I've been trying to find the solution to my problem.
I have several Heading Tags (H1, H2 etc) each in their own file.
I would like to add some css when calling them based on a prop. Some headings have a small border-bottom and some don't. So, in order to refractor my code, I want to add some css based on a prop. I can't seem to find a way.



Here's an example of Heading H2:



import styled from 'styled-components';
import colors from '../../../../colors';
import fonts from '../../../../fonts';
import fontWeights from '../../../../fontWeights';

const HeadingH2 = styled.h2`
color: ${colors.text};
font-family: ${fonts.montSerrat};
font-size: 1.6em;
font-weight: ${fontWeights.light};
letter-spacing: 0.2em;
padding-bottom: 0.7em;
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
`;

export default HeadingH2


Example of calling Heading H2:



import React from 'react';
import HeadingH2 from '../../common/headings/heading_h2';
import HeadingBaseline from '../../common/headings_baseline';


// Features
import {SectionContainer, FeaturesContainer} from './features.style';

import Feature from './feature';
import feature1 from '../../../img/features/feature1.png';
import feature2 from '../../../img/features/feature2.png';
import feature3 from '../../../img/features/feature3.png';

// Text
import Text from '../../../content';

const Features = () => {
return(
<SectionContainer id={"what"}>
<HeadingH2>
What We Do
</HeadingH2>
<HeadingBaseline>
{Text.headingBaseline}
</HeadingBaseline>
<FeaturesContainer>
<Feature
src={feature1}
headingText={Text.feature1.heading}
paragraph={Text.feature1.paragraph}
/>
<Feature
src={feature2}
headingText={Text.feature2.heading}
paragraph={Text.feature2.paragraph}
/>
<Feature
src={feature3}
headingText={Text.feature3.heading}
paragraph={Text.feature3.paragraph}
/>
</FeaturesContainer>
</SectionContainer>
)
};

export default Features;


I want to extract the following CSS properties



position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);


So, assuming I have the above CSS rule in a separate file, how do I add/import them using props on my styled component HeadingH2.



Thanks for the help :)







javascript reactjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 31 '18 at 17:42









zeduke

8518




8518










asked Dec 31 '18 at 14:08









allan00958allan00958

617




617













  • I've never used styled-components but there appears to be an example of what you want to do on the library's homepage. Essentially the styled component has access to props when building the CSS string and you could overwrite/add styles based on them.

    – numbers1311407
    Dec 31 '18 at 14:55













  • not quite. I need to be able to add css rules whenever I want and from a specific file. The example on the homapage is not modular at all.

    – allan00958
    Dec 31 '18 at 16:48



















  • I've never used styled-components but there appears to be an example of what you want to do on the library's homepage. Essentially the styled component has access to props when building the CSS string and you could overwrite/add styles based on them.

    – numbers1311407
    Dec 31 '18 at 14:55













  • not quite. I need to be able to add css rules whenever I want and from a specific file. The example on the homapage is not modular at all.

    – allan00958
    Dec 31 '18 at 16:48

















I've never used styled-components but there appears to be an example of what you want to do on the library's homepage. Essentially the styled component has access to props when building the CSS string and you could overwrite/add styles based on them.

– numbers1311407
Dec 31 '18 at 14:55







I've never used styled-components but there appears to be an example of what you want to do on the library's homepage. Essentially the styled component has access to props when building the CSS string and you could overwrite/add styles based on them.

– numbers1311407
Dec 31 '18 at 14:55















not quite. I need to be able to add css rules whenever I want and from a specific file. The example on the homapage is not modular at all.

– allan00958
Dec 31 '18 at 16:48





not quite. I need to be able to add css rules whenever I want and from a specific file. The example on the homapage is not modular at all.

– allan00958
Dec 31 '18 at 16:48












5 Answers
5






active

oldest

votes


















2














Something like this works:



const HeadingH2 = styled.h2`
position: ${props => props.relative && 'relative'};
padding: ${props => props.paddingBottom ? '0 0 20px 0' : '0'};
}
`;


Then use like this:



<HeadingH2 relative paddingBottom />





share|improve this answer
























  • I need to find a way to call those css properties from a separate file or something to reduce code repetitions

    – allan00958
    Dec 31 '18 at 16:00











  • This is the best answer for using props with styled-components

    – Ru Chern Chong
    Dec 31 '18 at 16:54











  • @allan00958 you can import the styled component. You can change the properties using React Props when you consume the component.

    – jsw324
    Dec 31 '18 at 20:53













  • @allan00958 Please mark this answer as correct if it worked for you :) Thanks!

    – jsw324
    Jan 2 at 14:19











  • @jsw324 No, this answer doesn't work for me at all. I posted my solution below.

    – allan00958
    Jan 8 at 10:04



















0














You should definely check this: typestyle



the best way you can write dynamic css (for me). Works perfectly with react, even with ssr if you need it...






share|improve this answer































    0














    Why not just have a headingLevel prop? and then pass it into the styled component? And just have one StyledHeader styled component as I'm guessing the code is the mostly the same in all the heading styles files? Which is a big no no, you want to always try not to repeat your code.



    const Features = () => {
    return(
    <SectionContainer id={"what"}>
    <StyledHeader
    headingLevel={headingLevel}
    >
    What We Do
    </StyledHeader>
    <HeadingBaseline>
    {Text.headingBaseline}
    </HeadingBaseline>
    <FeaturesContainer>
    <Feature
    src={feature1}
    headingText={Text.feature1.heading}
    paragraph={Text.feature1.paragraph}
    />
    <Feature
    src={feature2}
    headingText={Text.feature2.heading}
    paragraph={Text.feature2.paragraph}
    />
    <Feature
    src={feature3}
    headingText={Text.feature3.heading}
    paragraph={Text.feature3.paragraph}
    />
    </FeaturesContainer>
    </SectionContainer>
    )
    };

    export default Features;


    And in your StyledHeader file



    The below function will take your passed in heading level of h1, h2, h3 and will apply a border, if not the above 3 heading level it will be 0 value. I'd do some checks to ensure the value is lower case e.g. toLowerCase()



    const getBorder = ({ headingLevel } ) => {
    const headingLevelMap = {
    h1: 0.7,
    h2: 0.6,
    h3: 0.6,
    };

    return headingLevelMap[headingLevel] || 0;
    }

    const HeadingH2 = styled.headingLevel`
    color: ${colors.text};
    font-family: ${fonts.montSerrat};
    font-size: 1.6em;
    font-weight: ${fontWeights.light};
    letter-spacing: 0.2em;
    padding-bottom: 0.7em;
    border-bottom: ${getCorrectBorderBottom}em solid black
    position: relative;
    text-transform: uppercase;
    text-align: center;
    &:after{
    content: "";
    display: block;
    height: 3px;
    width: 45px;
    background-color: currentColor;
    /* position */
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    }
    `;


    I'd also check that if the value of the passed in headingLevel is not any of the 6 heading levels it should have a default value of whatever you want.



    The above was just quick pseudo code, but hopefully get the general idea here? Let me know it comments if not.



    I'd also recommend that you split your Title component out into a separate component.






    share|improve this answer


























    • I sort of get it but I think it's not the right solution. I found something that works using concatenation. I will update my original question.

      – allan00958
      Dec 31 '18 at 16:41











    • I posted my solution

      – allan00958
      Dec 31 '18 at 16:53



















    0














    Possible answer:



    I add the following CSS rules in a separate file like so.
    I create a function which returns a string of text. I can import this function and add those rules to any component I wish.



    export const borderBottom = () => {
    return `
    position: relative;
    text-transform: uppercase;
    text-align: center;
    &:after{
    content: "";
    display: block;
    height: 3px;
    width: 45px;
    background-color: currentColor;
    /* position */
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    }
    `
    }


    And use it like so on any heading or component that I wish:



    import styled from 'styled-components';
    import colors from '../../../../colors';
    import fonts from '../../../../fonts';
    import fontWeights from '../../../../fontWeights';
    import {borderBottom} from '../../../../css';

    const HeadingH5 = styled.h5`
    color: ${colors.black};
    font-family: ${fonts.montSerrat};
    font-size: 1em;
    font-weight: ${fontWeights.light};
    letter-spacing: 0.1em;
    padding-bottom: 0.45em;
    margin-bottom: 25px;
    ${borderBottom}
    `
    ;

    export default HeadingH5;


    This works for me. Any other suggestions are welcome.






    share|improve this answer


























    • Could you please explain what is the solution? It's nice that you provided an answer to your own question, but if you want others to benefit from it you should explain what you did to fix the problem and why. If you posted this as a continuation of your own problem, please update the question instead.

      – Dharman
      Dec 31 '18 at 21:52











    • I create a function that returns some CSS properties/values as string and import/export them using string substitution into any styled component that I wish. That way my code is dry and modular.

      – allan00958
      Dec 31 '18 at 23:14



















    0














    You can also use css helper from styled-components to create a SharedStyles.js file.



    In the demo you can see it in action.
    Just using it in a style of an inherited component is not working as expected. If I'm adding it to StyledBase then the variables are not correctly added afterwards (hover style override stops working).
    That's why I copied ${borderBottom} to each styled component Heading1 / Heading2 instead of adding it to StyledBase.



    I think having a level prop for the heading is a good idea but I would handle it differently by creating a HeadingBase component and add your styles to a StyledBase component (also see code in the demo).



    The HeadingBase code looks like this:



    const HeadingBase = ({ className, children, level = 1 }) =>
    React.createElement(`h${level}`, { className }, children);


    It's a component that renders h1,h2,... tags based on the prop level passed (defaults to h1). The h-tag receives className as props (needed for styled-components) and contains the children passed to the component.



    SharedStyles.js



    import { css } from "styled-components";

    export const borderBottom = css`
    &:after{
    content: "";
    display: block;
    height: 3px;
    width: 200px;
    background-color: ${props => props.color || "black"};
    /* position */
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    `;


    Then you can import it with import { borderBottom } from "./SharedStyles"; and add it to your styled-component like following:



    const Heading1= styled.h1`
    ${borderBottom}
    `;





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53988374%2freact-styled-component-how-to-add-css-styles-based-on-props%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Something like this works:



      const HeadingH2 = styled.h2`
      position: ${props => props.relative && 'relative'};
      padding: ${props => props.paddingBottom ? '0 0 20px 0' : '0'};
      }
      `;


      Then use like this:



      <HeadingH2 relative paddingBottom />





      share|improve this answer
























      • I need to find a way to call those css properties from a separate file or something to reduce code repetitions

        – allan00958
        Dec 31 '18 at 16:00











      • This is the best answer for using props with styled-components

        – Ru Chern Chong
        Dec 31 '18 at 16:54











      • @allan00958 you can import the styled component. You can change the properties using React Props when you consume the component.

        – jsw324
        Dec 31 '18 at 20:53













      • @allan00958 Please mark this answer as correct if it worked for you :) Thanks!

        – jsw324
        Jan 2 at 14:19











      • @jsw324 No, this answer doesn't work for me at all. I posted my solution below.

        – allan00958
        Jan 8 at 10:04
















      2














      Something like this works:



      const HeadingH2 = styled.h2`
      position: ${props => props.relative && 'relative'};
      padding: ${props => props.paddingBottom ? '0 0 20px 0' : '0'};
      }
      `;


      Then use like this:



      <HeadingH2 relative paddingBottom />





      share|improve this answer
























      • I need to find a way to call those css properties from a separate file or something to reduce code repetitions

        – allan00958
        Dec 31 '18 at 16:00











      • This is the best answer for using props with styled-components

        – Ru Chern Chong
        Dec 31 '18 at 16:54











      • @allan00958 you can import the styled component. You can change the properties using React Props when you consume the component.

        – jsw324
        Dec 31 '18 at 20:53













      • @allan00958 Please mark this answer as correct if it worked for you :) Thanks!

        – jsw324
        Jan 2 at 14:19











      • @jsw324 No, this answer doesn't work for me at all. I posted my solution below.

        – allan00958
        Jan 8 at 10:04














      2












      2








      2







      Something like this works:



      const HeadingH2 = styled.h2`
      position: ${props => props.relative && 'relative'};
      padding: ${props => props.paddingBottom ? '0 0 20px 0' : '0'};
      }
      `;


      Then use like this:



      <HeadingH2 relative paddingBottom />





      share|improve this answer













      Something like this works:



      const HeadingH2 = styled.h2`
      position: ${props => props.relative && 'relative'};
      padding: ${props => props.paddingBottom ? '0 0 20px 0' : '0'};
      }
      `;


      Then use like this:



      <HeadingH2 relative paddingBottom />






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Dec 31 '18 at 14:59









      jsw324jsw324

      45838




      45838













      • I need to find a way to call those css properties from a separate file or something to reduce code repetitions

        – allan00958
        Dec 31 '18 at 16:00











      • This is the best answer for using props with styled-components

        – Ru Chern Chong
        Dec 31 '18 at 16:54











      • @allan00958 you can import the styled component. You can change the properties using React Props when you consume the component.

        – jsw324
        Dec 31 '18 at 20:53













      • @allan00958 Please mark this answer as correct if it worked for you :) Thanks!

        – jsw324
        Jan 2 at 14:19











      • @jsw324 No, this answer doesn't work for me at all. I posted my solution below.

        – allan00958
        Jan 8 at 10:04



















      • I need to find a way to call those css properties from a separate file or something to reduce code repetitions

        – allan00958
        Dec 31 '18 at 16:00











      • This is the best answer for using props with styled-components

        – Ru Chern Chong
        Dec 31 '18 at 16:54











      • @allan00958 you can import the styled component. You can change the properties using React Props when you consume the component.

        – jsw324
        Dec 31 '18 at 20:53













      • @allan00958 Please mark this answer as correct if it worked for you :) Thanks!

        – jsw324
        Jan 2 at 14:19











      • @jsw324 No, this answer doesn't work for me at all. I posted my solution below.

        – allan00958
        Jan 8 at 10:04

















      I need to find a way to call those css properties from a separate file or something to reduce code repetitions

      – allan00958
      Dec 31 '18 at 16:00





      I need to find a way to call those css properties from a separate file or something to reduce code repetitions

      – allan00958
      Dec 31 '18 at 16:00













      This is the best answer for using props with styled-components

      – Ru Chern Chong
      Dec 31 '18 at 16:54





      This is the best answer for using props with styled-components

      – Ru Chern Chong
      Dec 31 '18 at 16:54













      @allan00958 you can import the styled component. You can change the properties using React Props when you consume the component.

      – jsw324
      Dec 31 '18 at 20:53







      @allan00958 you can import the styled component. You can change the properties using React Props when you consume the component.

      – jsw324
      Dec 31 '18 at 20:53















      @allan00958 Please mark this answer as correct if it worked for you :) Thanks!

      – jsw324
      Jan 2 at 14:19





      @allan00958 Please mark this answer as correct if it worked for you :) Thanks!

      – jsw324
      Jan 2 at 14:19













      @jsw324 No, this answer doesn't work for me at all. I posted my solution below.

      – allan00958
      Jan 8 at 10:04





      @jsw324 No, this answer doesn't work for me at all. I posted my solution below.

      – allan00958
      Jan 8 at 10:04













      0














      You should definely check this: typestyle



      the best way you can write dynamic css (for me). Works perfectly with react, even with ssr if you need it...






      share|improve this answer




























        0














        You should definely check this: typestyle



        the best way you can write dynamic css (for me). Works perfectly with react, even with ssr if you need it...






        share|improve this answer


























          0












          0








          0







          You should definely check this: typestyle



          the best way you can write dynamic css (for me). Works perfectly with react, even with ssr if you need it...






          share|improve this answer













          You should definely check this: typestyle



          the best way you can write dynamic css (for me). Works perfectly with react, even with ssr if you need it...







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 31 '18 at 15:10









          Juraj KocanJuraj Kocan

          1255




          1255























              0














              Why not just have a headingLevel prop? and then pass it into the styled component? And just have one StyledHeader styled component as I'm guessing the code is the mostly the same in all the heading styles files? Which is a big no no, you want to always try not to repeat your code.



              const Features = () => {
              return(
              <SectionContainer id={"what"}>
              <StyledHeader
              headingLevel={headingLevel}
              >
              What We Do
              </StyledHeader>
              <HeadingBaseline>
              {Text.headingBaseline}
              </HeadingBaseline>
              <FeaturesContainer>
              <Feature
              src={feature1}
              headingText={Text.feature1.heading}
              paragraph={Text.feature1.paragraph}
              />
              <Feature
              src={feature2}
              headingText={Text.feature2.heading}
              paragraph={Text.feature2.paragraph}
              />
              <Feature
              src={feature3}
              headingText={Text.feature3.heading}
              paragraph={Text.feature3.paragraph}
              />
              </FeaturesContainer>
              </SectionContainer>
              )
              };

              export default Features;


              And in your StyledHeader file



              The below function will take your passed in heading level of h1, h2, h3 and will apply a border, if not the above 3 heading level it will be 0 value. I'd do some checks to ensure the value is lower case e.g. toLowerCase()



              const getBorder = ({ headingLevel } ) => {
              const headingLevelMap = {
              h1: 0.7,
              h2: 0.6,
              h3: 0.6,
              };

              return headingLevelMap[headingLevel] || 0;
              }

              const HeadingH2 = styled.headingLevel`
              color: ${colors.text};
              font-family: ${fonts.montSerrat};
              font-size: 1.6em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.2em;
              padding-bottom: 0.7em;
              border-bottom: ${getCorrectBorderBottom}em solid black
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `;


              I'd also check that if the value of the passed in headingLevel is not any of the 6 heading levels it should have a default value of whatever you want.



              The above was just quick pseudo code, but hopefully get the general idea here? Let me know it comments if not.



              I'd also recommend that you split your Title component out into a separate component.






              share|improve this answer


























              • I sort of get it but I think it's not the right solution. I found something that works using concatenation. I will update my original question.

                – allan00958
                Dec 31 '18 at 16:41











              • I posted my solution

                – allan00958
                Dec 31 '18 at 16:53
















              0














              Why not just have a headingLevel prop? and then pass it into the styled component? And just have one StyledHeader styled component as I'm guessing the code is the mostly the same in all the heading styles files? Which is a big no no, you want to always try not to repeat your code.



              const Features = () => {
              return(
              <SectionContainer id={"what"}>
              <StyledHeader
              headingLevel={headingLevel}
              >
              What We Do
              </StyledHeader>
              <HeadingBaseline>
              {Text.headingBaseline}
              </HeadingBaseline>
              <FeaturesContainer>
              <Feature
              src={feature1}
              headingText={Text.feature1.heading}
              paragraph={Text.feature1.paragraph}
              />
              <Feature
              src={feature2}
              headingText={Text.feature2.heading}
              paragraph={Text.feature2.paragraph}
              />
              <Feature
              src={feature3}
              headingText={Text.feature3.heading}
              paragraph={Text.feature3.paragraph}
              />
              </FeaturesContainer>
              </SectionContainer>
              )
              };

              export default Features;


              And in your StyledHeader file



              The below function will take your passed in heading level of h1, h2, h3 and will apply a border, if not the above 3 heading level it will be 0 value. I'd do some checks to ensure the value is lower case e.g. toLowerCase()



              const getBorder = ({ headingLevel } ) => {
              const headingLevelMap = {
              h1: 0.7,
              h2: 0.6,
              h3: 0.6,
              };

              return headingLevelMap[headingLevel] || 0;
              }

              const HeadingH2 = styled.headingLevel`
              color: ${colors.text};
              font-family: ${fonts.montSerrat};
              font-size: 1.6em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.2em;
              padding-bottom: 0.7em;
              border-bottom: ${getCorrectBorderBottom}em solid black
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `;


              I'd also check that if the value of the passed in headingLevel is not any of the 6 heading levels it should have a default value of whatever you want.



              The above was just quick pseudo code, but hopefully get the general idea here? Let me know it comments if not.



              I'd also recommend that you split your Title component out into a separate component.






              share|improve this answer


























              • I sort of get it but I think it's not the right solution. I found something that works using concatenation. I will update my original question.

                – allan00958
                Dec 31 '18 at 16:41











              • I posted my solution

                – allan00958
                Dec 31 '18 at 16:53














              0












              0








              0







              Why not just have a headingLevel prop? and then pass it into the styled component? And just have one StyledHeader styled component as I'm guessing the code is the mostly the same in all the heading styles files? Which is a big no no, you want to always try not to repeat your code.



              const Features = () => {
              return(
              <SectionContainer id={"what"}>
              <StyledHeader
              headingLevel={headingLevel}
              >
              What We Do
              </StyledHeader>
              <HeadingBaseline>
              {Text.headingBaseline}
              </HeadingBaseline>
              <FeaturesContainer>
              <Feature
              src={feature1}
              headingText={Text.feature1.heading}
              paragraph={Text.feature1.paragraph}
              />
              <Feature
              src={feature2}
              headingText={Text.feature2.heading}
              paragraph={Text.feature2.paragraph}
              />
              <Feature
              src={feature3}
              headingText={Text.feature3.heading}
              paragraph={Text.feature3.paragraph}
              />
              </FeaturesContainer>
              </SectionContainer>
              )
              };

              export default Features;


              And in your StyledHeader file



              The below function will take your passed in heading level of h1, h2, h3 and will apply a border, if not the above 3 heading level it will be 0 value. I'd do some checks to ensure the value is lower case e.g. toLowerCase()



              const getBorder = ({ headingLevel } ) => {
              const headingLevelMap = {
              h1: 0.7,
              h2: 0.6,
              h3: 0.6,
              };

              return headingLevelMap[headingLevel] || 0;
              }

              const HeadingH2 = styled.headingLevel`
              color: ${colors.text};
              font-family: ${fonts.montSerrat};
              font-size: 1.6em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.2em;
              padding-bottom: 0.7em;
              border-bottom: ${getCorrectBorderBottom}em solid black
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `;


              I'd also check that if the value of the passed in headingLevel is not any of the 6 heading levels it should have a default value of whatever you want.



              The above was just quick pseudo code, but hopefully get the general idea here? Let me know it comments if not.



              I'd also recommend that you split your Title component out into a separate component.






              share|improve this answer















              Why not just have a headingLevel prop? and then pass it into the styled component? And just have one StyledHeader styled component as I'm guessing the code is the mostly the same in all the heading styles files? Which is a big no no, you want to always try not to repeat your code.



              const Features = () => {
              return(
              <SectionContainer id={"what"}>
              <StyledHeader
              headingLevel={headingLevel}
              >
              What We Do
              </StyledHeader>
              <HeadingBaseline>
              {Text.headingBaseline}
              </HeadingBaseline>
              <FeaturesContainer>
              <Feature
              src={feature1}
              headingText={Text.feature1.heading}
              paragraph={Text.feature1.paragraph}
              />
              <Feature
              src={feature2}
              headingText={Text.feature2.heading}
              paragraph={Text.feature2.paragraph}
              />
              <Feature
              src={feature3}
              headingText={Text.feature3.heading}
              paragraph={Text.feature3.paragraph}
              />
              </FeaturesContainer>
              </SectionContainer>
              )
              };

              export default Features;


              And in your StyledHeader file



              The below function will take your passed in heading level of h1, h2, h3 and will apply a border, if not the above 3 heading level it will be 0 value. I'd do some checks to ensure the value is lower case e.g. toLowerCase()



              const getBorder = ({ headingLevel } ) => {
              const headingLevelMap = {
              h1: 0.7,
              h2: 0.6,
              h3: 0.6,
              };

              return headingLevelMap[headingLevel] || 0;
              }

              const HeadingH2 = styled.headingLevel`
              color: ${colors.text};
              font-family: ${fonts.montSerrat};
              font-size: 1.6em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.2em;
              padding-bottom: 0.7em;
              border-bottom: ${getCorrectBorderBottom}em solid black
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `;


              I'd also check that if the value of the passed in headingLevel is not any of the 6 heading levels it should have a default value of whatever you want.



              The above was just quick pseudo code, but hopefully get the general idea here? Let me know it comments if not.



              I'd also recommend that you split your Title component out into a separate component.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 31 '18 at 15:24

























              answered Dec 31 '18 at 15:04









              zedukezeduke

              8518




              8518













              • I sort of get it but I think it's not the right solution. I found something that works using concatenation. I will update my original question.

                – allan00958
                Dec 31 '18 at 16:41











              • I posted my solution

                – allan00958
                Dec 31 '18 at 16:53



















              • I sort of get it but I think it's not the right solution. I found something that works using concatenation. I will update my original question.

                – allan00958
                Dec 31 '18 at 16:41











              • I posted my solution

                – allan00958
                Dec 31 '18 at 16:53

















              I sort of get it but I think it's not the right solution. I found something that works using concatenation. I will update my original question.

              – allan00958
              Dec 31 '18 at 16:41





              I sort of get it but I think it's not the right solution. I found something that works using concatenation. I will update my original question.

              – allan00958
              Dec 31 '18 at 16:41













              I posted my solution

              – allan00958
              Dec 31 '18 at 16:53





              I posted my solution

              – allan00958
              Dec 31 '18 at 16:53











              0














              Possible answer:



              I add the following CSS rules in a separate file like so.
              I create a function which returns a string of text. I can import this function and add those rules to any component I wish.



              export const borderBottom = () => {
              return `
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `
              }


              And use it like so on any heading or component that I wish:



              import styled from 'styled-components';
              import colors from '../../../../colors';
              import fonts from '../../../../fonts';
              import fontWeights from '../../../../fontWeights';
              import {borderBottom} from '../../../../css';

              const HeadingH5 = styled.h5`
              color: ${colors.black};
              font-family: ${fonts.montSerrat};
              font-size: 1em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.1em;
              padding-bottom: 0.45em;
              margin-bottom: 25px;
              ${borderBottom}
              `
              ;

              export default HeadingH5;


              This works for me. Any other suggestions are welcome.






              share|improve this answer


























              • Could you please explain what is the solution? It's nice that you provided an answer to your own question, but if you want others to benefit from it you should explain what you did to fix the problem and why. If you posted this as a continuation of your own problem, please update the question instead.

                – Dharman
                Dec 31 '18 at 21:52











              • I create a function that returns some CSS properties/values as string and import/export them using string substitution into any styled component that I wish. That way my code is dry and modular.

                – allan00958
                Dec 31 '18 at 23:14
















              0














              Possible answer:



              I add the following CSS rules in a separate file like so.
              I create a function which returns a string of text. I can import this function and add those rules to any component I wish.



              export const borderBottom = () => {
              return `
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `
              }


              And use it like so on any heading or component that I wish:



              import styled from 'styled-components';
              import colors from '../../../../colors';
              import fonts from '../../../../fonts';
              import fontWeights from '../../../../fontWeights';
              import {borderBottom} from '../../../../css';

              const HeadingH5 = styled.h5`
              color: ${colors.black};
              font-family: ${fonts.montSerrat};
              font-size: 1em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.1em;
              padding-bottom: 0.45em;
              margin-bottom: 25px;
              ${borderBottom}
              `
              ;

              export default HeadingH5;


              This works for me. Any other suggestions are welcome.






              share|improve this answer


























              • Could you please explain what is the solution? It's nice that you provided an answer to your own question, but if you want others to benefit from it you should explain what you did to fix the problem and why. If you posted this as a continuation of your own problem, please update the question instead.

                – Dharman
                Dec 31 '18 at 21:52











              • I create a function that returns some CSS properties/values as string and import/export them using string substitution into any styled component that I wish. That way my code is dry and modular.

                – allan00958
                Dec 31 '18 at 23:14














              0












              0








              0







              Possible answer:



              I add the following CSS rules in a separate file like so.
              I create a function which returns a string of text. I can import this function and add those rules to any component I wish.



              export const borderBottom = () => {
              return `
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `
              }


              And use it like so on any heading or component that I wish:



              import styled from 'styled-components';
              import colors from '../../../../colors';
              import fonts from '../../../../fonts';
              import fontWeights from '../../../../fontWeights';
              import {borderBottom} from '../../../../css';

              const HeadingH5 = styled.h5`
              color: ${colors.black};
              font-family: ${fonts.montSerrat};
              font-size: 1em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.1em;
              padding-bottom: 0.45em;
              margin-bottom: 25px;
              ${borderBottom}
              `
              ;

              export default HeadingH5;


              This works for me. Any other suggestions are welcome.






              share|improve this answer















              Possible answer:



              I add the following CSS rules in a separate file like so.
              I create a function which returns a string of text. I can import this function and add those rules to any component I wish.



              export const borderBottom = () => {
              return `
              position: relative;
              text-transform: uppercase;
              text-align: center;
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 45px;
              background-color: currentColor;
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              }
              `
              }


              And use it like so on any heading or component that I wish:



              import styled from 'styled-components';
              import colors from '../../../../colors';
              import fonts from '../../../../fonts';
              import fontWeights from '../../../../fontWeights';
              import {borderBottom} from '../../../../css';

              const HeadingH5 = styled.h5`
              color: ${colors.black};
              font-family: ${fonts.montSerrat};
              font-size: 1em;
              font-weight: ${fontWeights.light};
              letter-spacing: 0.1em;
              padding-bottom: 0.45em;
              margin-bottom: 25px;
              ${borderBottom}
              `
              ;

              export default HeadingH5;


              This works for me. Any other suggestions are welcome.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 31 '18 at 23:06

























              answered Dec 31 '18 at 16:52









              allan00958allan00958

              617




              617













              • Could you please explain what is the solution? It's nice that you provided an answer to your own question, but if you want others to benefit from it you should explain what you did to fix the problem and why. If you posted this as a continuation of your own problem, please update the question instead.

                – Dharman
                Dec 31 '18 at 21:52











              • I create a function that returns some CSS properties/values as string and import/export them using string substitution into any styled component that I wish. That way my code is dry and modular.

                – allan00958
                Dec 31 '18 at 23:14



















              • Could you please explain what is the solution? It's nice that you provided an answer to your own question, but if you want others to benefit from it you should explain what you did to fix the problem and why. If you posted this as a continuation of your own problem, please update the question instead.

                – Dharman
                Dec 31 '18 at 21:52











              • I create a function that returns some CSS properties/values as string and import/export them using string substitution into any styled component that I wish. That way my code is dry and modular.

                – allan00958
                Dec 31 '18 at 23:14

















              Could you please explain what is the solution? It's nice that you provided an answer to your own question, but if you want others to benefit from it you should explain what you did to fix the problem and why. If you posted this as a continuation of your own problem, please update the question instead.

              – Dharman
              Dec 31 '18 at 21:52





              Could you please explain what is the solution? It's nice that you provided an answer to your own question, but if you want others to benefit from it you should explain what you did to fix the problem and why. If you posted this as a continuation of your own problem, please update the question instead.

              – Dharman
              Dec 31 '18 at 21:52













              I create a function that returns some CSS properties/values as string and import/export them using string substitution into any styled component that I wish. That way my code is dry and modular.

              – allan00958
              Dec 31 '18 at 23:14





              I create a function that returns some CSS properties/values as string and import/export them using string substitution into any styled component that I wish. That way my code is dry and modular.

              – allan00958
              Dec 31 '18 at 23:14











              0














              You can also use css helper from styled-components to create a SharedStyles.js file.



              In the demo you can see it in action.
              Just using it in a style of an inherited component is not working as expected. If I'm adding it to StyledBase then the variables are not correctly added afterwards (hover style override stops working).
              That's why I copied ${borderBottom} to each styled component Heading1 / Heading2 instead of adding it to StyledBase.



              I think having a level prop for the heading is a good idea but I would handle it differently by creating a HeadingBase component and add your styles to a StyledBase component (also see code in the demo).



              The HeadingBase code looks like this:



              const HeadingBase = ({ className, children, level = 1 }) =>
              React.createElement(`h${level}`, { className }, children);


              It's a component that renders h1,h2,... tags based on the prop level passed (defaults to h1). The h-tag receives className as props (needed for styled-components) and contains the children passed to the component.



              SharedStyles.js



              import { css } from "styled-components";

              export const borderBottom = css`
              &:after{
              content: "";
              display: block;
              height: 3px;
              width: 200px;
              background-color: ${props => props.color || "black"};
              /* position */
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              `;


              Then you can import it with import { borderBottom } from "./SharedStyles"; and add it to your styled-component like following:



              const Heading1= styled.h1`
              ${borderBottom}
              `;





              share|improve this answer




























                0














                You can also use css helper from styled-components to create a SharedStyles.js file.



                In the demo you can see it in action.
                Just using it in a style of an inherited component is not working as expected. If I'm adding it to StyledBase then the variables are not correctly added afterwards (hover style override stops working).
                That's why I copied ${borderBottom} to each styled component Heading1 / Heading2 instead of adding it to StyledBase.



                I think having a level prop for the heading is a good idea but I would handle it differently by creating a HeadingBase component and add your styles to a StyledBase component (also see code in the demo).



                The HeadingBase code looks like this:



                const HeadingBase = ({ className, children, level = 1 }) =>
                React.createElement(`h${level}`, { className }, children);


                It's a component that renders h1,h2,... tags based on the prop level passed (defaults to h1). The h-tag receives className as props (needed for styled-components) and contains the children passed to the component.



                SharedStyles.js



                import { css } from "styled-components";

                export const borderBottom = css`
                &:after{
                content: "";
                display: block;
                height: 3px;
                width: 200px;
                background-color: ${props => props.color || "black"};
                /* position */
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                `;


                Then you can import it with import { borderBottom } from "./SharedStyles"; and add it to your styled-component like following:



                const Heading1= styled.h1`
                ${borderBottom}
                `;





                share|improve this answer


























                  0












                  0








                  0







                  You can also use css helper from styled-components to create a SharedStyles.js file.



                  In the demo you can see it in action.
                  Just using it in a style of an inherited component is not working as expected. If I'm adding it to StyledBase then the variables are not correctly added afterwards (hover style override stops working).
                  That's why I copied ${borderBottom} to each styled component Heading1 / Heading2 instead of adding it to StyledBase.



                  I think having a level prop for the heading is a good idea but I would handle it differently by creating a HeadingBase component and add your styles to a StyledBase component (also see code in the demo).



                  The HeadingBase code looks like this:



                  const HeadingBase = ({ className, children, level = 1 }) =>
                  React.createElement(`h${level}`, { className }, children);


                  It's a component that renders h1,h2,... tags based on the prop level passed (defaults to h1). The h-tag receives className as props (needed for styled-components) and contains the children passed to the component.



                  SharedStyles.js



                  import { css } from "styled-components";

                  export const borderBottom = css`
                  &:after{
                  content: "";
                  display: block;
                  height: 3px;
                  width: 200px;
                  background-color: ${props => props.color || "black"};
                  /* position */
                  position: absolute;
                  bottom: 0;
                  left: 50%;
                  transform: translateX(-50%);
                  `;


                  Then you can import it with import { borderBottom } from "./SharedStyles"; and add it to your styled-component like following:



                  const Heading1= styled.h1`
                  ${borderBottom}
                  `;





                  share|improve this answer













                  You can also use css helper from styled-components to create a SharedStyles.js file.



                  In the demo you can see it in action.
                  Just using it in a style of an inherited component is not working as expected. If I'm adding it to StyledBase then the variables are not correctly added afterwards (hover style override stops working).
                  That's why I copied ${borderBottom} to each styled component Heading1 / Heading2 instead of adding it to StyledBase.



                  I think having a level prop for the heading is a good idea but I would handle it differently by creating a HeadingBase component and add your styles to a StyledBase component (also see code in the demo).



                  The HeadingBase code looks like this:



                  const HeadingBase = ({ className, children, level = 1 }) =>
                  React.createElement(`h${level}`, { className }, children);


                  It's a component that renders h1,h2,... tags based on the prop level passed (defaults to h1). The h-tag receives className as props (needed for styled-components) and contains the children passed to the component.



                  SharedStyles.js



                  import { css } from "styled-components";

                  export const borderBottom = css`
                  &:after{
                  content: "";
                  display: block;
                  height: 3px;
                  width: 200px;
                  background-color: ${props => props.color || "black"};
                  /* position */
                  position: absolute;
                  bottom: 0;
                  left: 50%;
                  transform: translateX(-50%);
                  `;


                  Then you can import it with import { borderBottom } from "./SharedStyles"; and add it to your styled-component like following:



                  const Heading1= styled.h1`
                  ${borderBottom}
                  `;






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 1 at 15:05









                  AWolfAWolf

                  6,44222132




                  6,44222132






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53988374%2freact-styled-component-how-to-add-css-styles-based-on-props%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas