1

I have a component that receives bunch of values as props, amongst them is a prop with a string value that defines the type of 'output html to return'.

something like this, which is of course wrong

const WithScrollingText = ({text,boxWidth,tag}) => {
    return boxWidth > 100
    ?   <tag>{text}</tag>
    :   <div className="with-scrolling-text"><div>{text}</div></div>
}

and I would call/use this component like this:

<WithScrollingText text="Something" boxWidth={250} tag="span"/>
<WithScrollingText text="Something else" boxWidth={250} tag="div"/>

and so on

How can I fix the rendering so that when I send 'span' to the component, it renders and returns an span

1 Answer 1

5

JSX is just syntactic sugar. Babel transforms <div>Hello</div> into React.createElement("div", {}, "Hello").

So in order to have a dynamic tag name, you can use this syntax directly:

const WithScrollingText = ({text, boxWidth, tag}) => {
    return boxWidth > 100
    ? React.createElement(tag, {}, text)
    : <div className="with-scrolling-text"><div>{text}</div></div>
}

Another approach, should you want to stick with a JSX-style tag, is simply to assign the value of tag to a variable with a capital first letter—this tells React to evaluate it as a variable instead of treating it as a string (like it would for React elements, like div).

const WithScrollingText = ({text, boxWidth, tag}) => {
  const Tag = tag
  return boxWidth > 100
    ? <Tag>{text}</Tag>
    : <div className="with-scrolling-text"><div>{text}</div></div>
}
Sign up to request clarification or add additional context in comments.

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.