0

For example, I want to do this:

const DynamicComponent = condition ? MyComponent : React.div;

const usedDynamicComponent = <DynamicComponent> How cool? </DynamicComponent>;

What do I use there instead of React.div, which is a thing I just made up?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
eye_mew
  • 8,855
  • 7
  • 30
  • 50

2 Answers2

1
const DynamicComponent = condition ? MyComponent : <div>{this.props.children}</div>;

const usedDynamicComponent = <DynamicComponent> How cool? </DynamicComponent>;
Dresha
  • 96
  • 1
  • 5
1

You can access the this.props.children to make a layout kind of thing. You can access the child of some component inside itself by using this.props.children.

class Div extends Component {
  render() {
    return <div {...this.props} >{this.props.children}</div>;
  }
}

This will wrap anything you put inside the Div tag between the HTML div tag. To access the props of the component given to the <Div>, you can simply add {...this.props}, it will add all your props on the actual div.

You can use the above-given component like:

<Div className="custom" custom_prop="value"><AnyReactComponent /></Div>

will convert to:

<div className="custom" custom_prop="value"><AnyReactComponent /></div>
Raghav Garg
  • 3,601
  • 2
  • 23
  • 32
  • That works but I was hoping it was possible to directly reference react's `div` class instead of wrapping it, which feels doesn't feel as elegant. But maybe this is the best we can do :) – eye_mew Sep 10 '17 at 20:24
  • Also this wouldn't pass any props passed to `Div` to the underlying div, like `className` for example. – eye_mew Sep 10 '17 at 20:28