DEV Community

Maciej Trzciński 🌱🇵🇱
Maciej Trzciński 🌱🇵🇱

Posted on

Store text inside variables instead of inline.

Why does text stored inside variables give you flexibility and control?

Before I wrote this article, I’ve tried a couple of times to write down my thoughts. Let me explain first what I called inline:

<CopyText.Heading tag="h2">
  Lorem Ipsum dolores set.
</CopyText.Heading>
Enter fullscreen mode Exit fullscreen mode

This example showed you what I meant as an inline text.

Let’s go straight forward to the point:
When you are a programmer, and you have been writing the code. One of the most important parts is clarity of your own code. The clarity sometimes defines if you’re engaged.

I wrote some rules how our code could be more efficient by using vars instead of pure text.

Firstly, when you got the message from the marketing team with new needs, you as a programmer gonna replace the text manually. Trust me, it isn’t easy to find text covered by components. Since I have been using const instead of inline text, my life become easier.

const title = `Title`;
const description = `Description`;

// component 
<Component>
  <Title>{title}</Title>
  <Description>{description}</Description>
</Component>
Enter fullscreen mode Exit fullscreen mode

Secondly, client or even you during the project lifecycle can decide to use API to manage the page. When you got all text stored inside variables, the change is easy-peasy to the implementation.

// old variables
const title = `Title`;
const description = `Description`;

// new API
const { title, description } = API();

// component 
<Component>
  <Title>{title}</Title>
  <Description>{description}</Description>
</Component>
Enter fullscreen mode Exit fullscreen mode

Thirdly, in some cases, the structure requires displaying column of the same components with different content. It’s easier to use map and display each component in simple way, than copying one by one - this solution reduce code and complexity.

const data = [
  {
    title: `Title`,
    description: 'Description',
  },
  {
    title: `Title`,
    description: `Description`,
  },
  {
    title: `Title`,
    description: `Description`,
  },
];

// component 
<Parent>
  {data.map(({ title, description}) => (
    <Component>
      <Title>{title}</Title>
      <Description>{description}</Description>
    </Component>
  ))}
</Parent>
Enter fullscreen mode Exit fullscreen mode

Key takeaways:

  • const variable is easier to find and replace
  • const variable reduce complexity of components

Discussion (0)