skip to Main Content

I have this element:

<div className={`my_container ${theme} ${isSpanishLanguage && 'spanishLanguage'} ${isEnglishLanguage && 'englishLanguage'}`}></div>

And I ge the error that my line is too long. How can I split this line into multiple lines to avoid getting this error ?

3

Answers


  1. Write a function like:

    function getClassName(isSpanishLanguage, isEnglishLanguage) {
      const classes = ['my_container'];
      if (isSpanishLanguage) {
        classes.push('spanishLanguage');
      }
      if (isEnglishLanguage) {
        classes.push('englishLanguage');
      }
      return classes.join(' ');
    }
    

    And call it with the appropriate params (even outside of jsx), or use a package like clsx.

    Login or Signup to reply.
  2. You could just rewrite that line like this:

    <div
      className={`my_container ${theme} ${isSpanishLanguage && "spanishLanguage"}
    ${isEnglishLanguage && "englishLanguage"}`}
    ></div>;
    

    However you shouldn’t be doing this manually, you should be relying on a tool like prettier to do this for you automatically upon saving your work.

    Or if you could just disable the eslint rule that complains about the length of your code line.

    Login or Signup to reply.
  3. It is a lint error but I would like to suggest you one library for joining classes in your react app systematically.

    I would suggest using https://www.npmjs.com/package/classnames package. It allow you to join classes conditionally.

    So the approach would be like

     <div className = {classNames(
                      [my_container] , [${theme}],
                      {[spanishLanguage]:isSpanishLanguage,
                        [englishLanguage]:isEnglishLanguage,
                      }
                     )
                    }>
     </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search