0
\$\begingroup\$

I'm working on an astrology project, and I have a component for each sign:

function Sign({ name, image }) {
  return (
    <div class="tile is-parent">
     <article class="tile is-child box">
        <div class="card-image">
          <img src={image} alt="Image"></img>
        </div>
        <p class="title">{name}</p>
        </article>
    </div>
  );
}

I also have a row that I'm going to repeat s times to create a table of all the signs of the zodiac:

import Sign from "./Sign";
import zodiacInfo from "./zodiac";

function getSign(_sign) {
  return zodiacInfo[_sign]["sign"];
}

function getImage(_sign) {
  return zodiacInfo[_sign]["image"];
}

function Row() {
  return (
    <div class="tile is-ancestor">
      <div class="tile is-parent">
        <Sign name={getSign("Ares")} image={getImage("Ares")} />
      </div>

      <div class="tile is-parent">
        <Sign name={getSign("Torus")} image={getImage("Torus")} />
      </div>

      <div class="tile is-parent">
        <Sign name={getSign("Gemini")} image={getImage("Gemini")} />
      </div>

      <div class="tile is-parent">
        <Sign name={getSign("Cancer")} image={getImage("Cancer")} />
      </div>
    </div>
  );
}

export default Row;

It feels like I'm being very inefficient. To make the next two rows, I'm going to have to repeat the row code 2 more times and enter all the sign names by hand. Is there a more efficient way to do this?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can put the strings into an array and map through them:

import Sign from "./Sign";
import zodiacInfo from "./zodiac";

const names = ["Ares", "Torus", "Gemini", "Cancer"]; // you can add the rest in here

function getSign(_sign) {
  return zodiacInfo[_sign]["sign"];
}

function getImage(_sign) {
  return zodiacInfo[_sign]["image"];
}

function Row() {
  return (
    <div class="tile is-ancestor">
      {names.map(name => (
          <div class="tile is-parent">
              <Sign name={getSign(name)} image={getImage(name)} />
          </div>
      ))}
    </div>
  );
}

export default Row;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.