0

I notice quite a lot of my code is duplicated purely because I do not know how to refactor it differently taking a variable into consideration.

This is the code inside my react render method:

          if (card.suit == 'D' || card.suit == 'H'){
            return <div className="cardFormatDH" key={ index }> {card.rankKey}{card.suit} </div>;
          }
          else if (card.suit == 'C' || card.suit == 'S'){
            return <div className="cardFormatCS" key={ index }> {card.rankKey}{card.suit} </div>;
          }

effectively what I would like to say is something like:

return exactly the same thing whether it is d/h or c/s, just allow c/s to have the same style and d/h to have the same style. also my if condition is quite long but I cant figure a way to shorten it down

2
  • The question might be better phrased as "Deleting Code Duplication in JSX" because this kind of stuff is trivial in normal JavaScript, but with all the weirdness of JSX, you're right, it isn't obvious at all! Commented Jan 11, 2017 at 19:19
  • 1
    JSX looks weird at a glance but that's where the weirdness ends. As syntactic sugar goes it's extraordinarily simple and this is no less trivial in JSX than in JavaScript. Commented Jan 11, 2017 at 19:37

3 Answers 3

4

You could create a suit -> className map:

const cls = {
  D: 'DH',
  H: 'DH',
  C: 'CS',
  S: 'CS',
};

and look up the suit in the table, using the value as part of the class name:

if (cls[card.suit]) {
  return <div className={`cardFormat${cls[card.suit]}`} key={ index }> {card.rankKey}{card.suit} </div>;
}
Sign up to request clarification or add additional context in comments.

1 Comment

should be cardFormat${cls[card.suit]}
1

You could write a getCardClassname function:

function getCardClassname(suit) {
  if (card.suit == 'D' || card.suit == 'H'){
    return "cardFormatDH";
  }
  else if (card.suit == 'C' || card.suit == 'S'){
    return "cardFormatCS";
  }
}

return <div className={getCardClassname(card.suit)} key={ index }> {card.rankKey}{card.suit} </div>;

Comments

0
  // you can add more pairs here 
  const formats = [ ['D', 'H'], ['C', 'S'] ]; 

  for(let format of formats) {
    if(format.includes(card.suit)) {
      return (
        <div className=`cardFormat${format.join('')}` key={ index }> 
          {card.rankKey}{card.suit} 
        </div>
      );
    }
  } 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.