Mateus Felipe
Mateus Felipe

Reputation: 1161

ReactJS: programmatically change component tag with JSX

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?

Upvotes: 2

Views: 2362

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

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

Upvotes: 3

oobgam
oobgam

Reputation: 1309

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/

Upvotes: 3

Related Questions