Why would we want to use variables to set a component's attributes?

Question

Why would we want to use variables to set a component’s attributes?

Answer

We can use variables, including object properties, to set a component’s attributes to keep our component easy to read and organized, but more importantly, we can use variables to set attributes so that our attributes can be dynamic and/or can be changed easily!

Consider the following examples, given that we may change the component’s attributes multiple times:
This first example would be eaiser to make changes to the attributes:

import React from 'react';
import ReactDOM from 'react-dom';

let myAttributes = { //here we can easily change the path to the image and the description because we can find our attributes easily at the top of our file and don't have to search through our component for them
  attrOne: 'path/to/image', 
  attrTwo: 'description of image'
}

class MyComponent extends React.Component {
  render() {
    return (
      <section>
        <h1>Hello World</h1>
        <img src={myAttributes.attrOne} alt={myAttributes.attrTwo} />
      </section>
    )
  }
}

ReactDOM.render(
  <MyComponent />,
  document.getElementById('app')
);

Whereas this would be more difficult to make changes to:

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {
  render() {
    return ( //the attributes here would be more difficult to change when we want to change the src path and/or the alt attribute because we would have to search through the file for the attributes we want to change
      <section> 
        <h1>Hello World</h1>
        <img src='path/to/image' alt='description of image' /> 
      </section>
    )
  }
}

ReactDOM.render(
  <MyComponent />,
  document.getElementById('app')
);
8 Likes