2

In code below I need to display in <h1> a text depending on what props will be passed. If props == "a" text should be from text_a, if props == "b" text from text_b;

const Header = (props) => {

const text_a = "Lorem ipsum dolor";
const text_b = "Lorem"

return (
<h1>{here should be a text from const}</h1>
);
}

I know that i can use ternary operator but I wondering if it possible to use template literals in this case something like that:

<h1>{`text_${props}`}</h1>

but in this case it dispaly literally "text_a" or "text_b" but not not what is assigned to the variable.

Thank for your help.

Tomasz
  • 55
  • 4

1 Answers1

1

If I understand the question, you want to render depending on the values passed to props, something like:

const TEXT = {
  text_a: "Lorem ipsum dolor",
  text_b: "Lorem",
};

const Header = (props) => {
  return <h1>{TEXT[props.text] || "Default Text"}</h1>;
};

// "Lorem ipsum dolor"
<Header text="text_a" />;
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • 1
    I was thinking about a slightly different solution but yours seems much simpler and cleaner. Thanks a lot – Tomasz May 19 '20 at 11:26