Search code examples
javascriptreactjsecmascript-6material-uitemplate-literals

How to add css to template literals in ES6 with react


I am trying to use the Material UI stepper in react.

The content of the step is setup as a string literal.

I want to add CSS (for paragraphs) inside the step content.

A lot of blog posts about this say that \n should work to make a br tag (for example: https://dev.to/sarah_chima/an-introduction-to-es6-template-literals-94l), however that \n just gets ignored when I try it.

How can I convert this:

function getStepContentResearcher(step) {
    switch (step) {
      case 0:
        return `para 1. \n para 2`;

Into two paragraphs:

function getStepContentResearcher(step) {
    switch (step) {
      case 0:
        return `para 1. 
                \n 
                para 2`;

Solution

  • One simple way is to return an array.

    case 0:
       return [`para 1.`, <br />, `para 2`];
    

    Another way is to use an inline component.

    case 0:
          return <>para 1. <br />, para 2</>;
    

    Third way is to provide style to the Typography or the content you are using with material ui makeStyles.

    instructions: {
        marginTop: theme.spacing(1),
        marginBottom: theme.spacing(1),
        whiteSpace: "pre-line" //<---like this
      }
    

    Working demo (includes all 3 options)

    full code snippet

    const useStyles = makeStyles(theme => ({
      root: {
        width: "100%"
      },
      button: {
        marginRight: theme.spacing(1)
      },
      instructions: {
        marginTop: theme.spacing(1),
        marginBottom: theme.spacing(1),
        whiteSpace: "pre-line"
      }
    }));
    
    function getSteps() {
      return ["Select campaign settings", "Create an ad group", "Create an ad"];
    }
    
    function getStepContent(step) {
      switch (step) {
        case 0:
          return [`para 1.`, <br />, `para 2`];
        case 1:
          return (
            <>
              para 1. <br />, para 2
            </>
          );
        case 2:
          return `This is the bit \n I really care about!`;
        default:
          return "Unknown step";
      }
    }