2

I am making a conditional component that returns <a> if href is defined and returns <div> if not. I am doing this way:

const Label = ({children, ...other}) => {
    let component;
    if (other.href)
        component =
            <a {...other}>
                { children }
            </a>
    else
        component =
            <div {...other}>
                { children }
            </div>

    return component;
}

export default Label

There is any way to make this component by only changing the tag name? I know that if I use the manual way of creating compontents (React.createElement) I can do this by changing the first argument passed, for it's a string. But with JSX it's a little different. I though something like

let component =
    <{tag} {...other}>
        { children }
    </{tag}>

Is it possible?

2 Answers 2

3

something like this?

const Label = ({children, ...other}) => {
  let component;

  if (other.href) {
    component = <a {...other}>{ children }</a>;
  } else if (other.tag) {
    const Tag = other.tag;
    component = <Tag {...other}>{ children }</Tag>;
  } else {
    component = <div {...other}>{ children }</div>;
  }
  return component;
}

ReactDOM.render(
    <Label href="#">Hello World</Label>,
  document.getElementById('root')
 );

 ReactDOM.render(
    <Label>Not a Link</Label>,
  document.getElementById('rootTwo')
 );


 ReactDOM.render(
    <Label tag="p">Paragraph</Label>,
  document.getElementById('rootThree')
 );

Working demo:, https://jsfiddle.net/tgm4htac/

Sign up to request clarification or add additional context in comments.

2 Comments

You can try the Babel repl const Tag = 'p'; <Tag >Hello</Tag>; transpiles to this var Tag = 'p'; React.createElement( Tag, null, 'Hello' ); I think you just need the jsx tag as a variable, not sure if it needs to be capitalized
It's valuable to note that Tag must be capitalized, because React interpeter lowercased as html tags.
3

If you pass to <> values like component.tag and JSX transpiler can create dynamic tags.

const Label = ({children, tag, ...other}) => {
  const component = { tag: tag };

  return (<component.tag {...other}>
    { children }
  </component.tag>);
};

Example

or

const Label = ({children, tag, ...other}) => {
  const Component = tag;

  return (<Component {...other}>
    { children }
  </Component>);
};

Example

1 Comment

This is the correct answer. Specifically the second example in my case.

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.