ReactJS: programmatically change component tag with JSX

- 1 answer

Ad

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?

Ad

Answer

Ad

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 target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" 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/

Ad
source: stackoverflow.com
Ad