Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  9] [ 5]  / answers: 1 / hits: 25128  / 8 Years ago, fri, december 23, 2016, 12:00:00

I am trying to pass a wrapper component as props. Is something like this technically possible in React?



import React, {Component, PropTypes} from 'react';
import ChildComp from './child-comp';

class Comp extends Component {
render() {
const { Wrapper } = this.props;
return (
<Wrapper>
<ChildComp />
</Wrapper>
);
}
}

Comp.propTypes = {};

export default Comp;

More From » reactjs

 Answers
14

Yes, it is perfectly possible, and commonly used. The only thing is, as a convention, in JSX capitalized words mean a user defined component, so you'll need to have your properties lowercased and you must capitalize the variable used to hold the component's reference.



import React from 'react';

function HelloWorld () {
return (
<span>
<Foo wrapper={Bar}/>
<Foo wrapper=h5/>
</span>
);
}

class Bar extends React.Component {
render() {
return <h1>{this.props.children}</h1>
}
}

class Foo extends React.Component {
render() {
// the variable name must be capitalized
const Wrapper = this.props.wrapper;
return (
<Wrapper><p>This works!</p></Wrapper>
);
}
}


For native components you can pass a String, like so: <Foo wrapper=h1/>. This works because JSX is just a syntax sugar for React.createElement('h1',props, children)


[#59589] Wednesday, December 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
;