2

I need a reusable component with any markup type decided inside at the coding time, so hardcoding different component would be a very complicating solution, so handling the markup using a function's style would be just awesome.

Here my sandbox:https://codesandbox.io/s/determined-clarke-gvrzv?fontsize=14

I would modify my html markup dynamically depending on a javascript variable, as following:

let markup= "li"
function App() {
 return (
    <div className="App">
      <[markup]>Hello World</[markup]> 
    </div>
 );
}

the console returns me:

Unexpected token

How handle this problem?

Thanks for any hint!

1

1 Answer 1

2

You can do:

const Markup = "li";

return (
  <div className="app">
    <Markup>Hello World</Markup>
  </div>
)

I don't know exactly what you're trying to do, but you might also consider conditionally rendering a different component:

const temperature = -20;

return (
  temperature < 30 ? <Cold /> : <Warm />
);

or conditionally swapping the markup inline:

const isCold = temp => temp < 30;

const temperature = -12;

return (
  isCold(temperature) ? <div>Brrr!</div> : <span>Sunshine!</span>
);

And finally, if you have many possible variants, you can establish a getComponent function to figure out what to render:

const SeasonalComponents = [
  {
    handles: temp => temp < 0,
    component: () => <div>Brrr!</div>
  },
  {
    handles: temp => temp < 30,
    component: () => <div>Get your coat!</div>
  },
  {
    handles: temp => temp < 50,
    component: () => <div>Just a jacket</div>
  },
  {
    handles: temp => temp < 100,
    component: () => <ImportedSummerComponent />
  }
];

function getComponent (temperature) {
  const seasonal = SeasonalComponents.find(x => x.handles(temperature);
  return seasonal ? seasonal.component : <span>Unseasonable weather!</span>;
}

which allows your render method to do a lookup:

const Component = getComponent(this.props.temp);

return (
  <Component />
);
Sign up to request clarification or add additional context in comments.

3 Comments

awesome, works fine, I need a reusable component with any markup type decided inside at the coding time, so hardcoding different component would be a very complicating solution :/, that said, the cap's Markup works just fine :)!
just remember to use uppercased the first char of variable name
I added an example of a component lookup pattern for cases where there are many possibilities.

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.