Search code examples
reactjstemplate-literalsvariable-names

template literals to display the variable name - React.js


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.


Solution

  • 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" />;