score:241
You can use this.props.children
to render whatever children the component contains:
const Wrap = ({ children }) => <div>{children}</div>
export default () => <Wrap><h1>Hello word</h1></Wrap>
score:-1
you can pass your react component into another component and emit the function from child
import CustomerFilters;
parent:
const handleFilterChange = (value) => {
console.log(value)
}
<DataGrid
contentName="customer"
fetchFilterComponents = {<CustomerFilters onSelectFilter={handleFilterChange} />}
</DataGrid>
child:
CustomerFilters
return (
<select className="filters-dropdown" onChange={onSelectFilter}>
<option>Select Filter</option>
{customerFilterOptions?.map((filter: any) => {
return <option value={filter.value}>{filter.name}</option>;
})}
</select>
)
score:0
You can pass your component as a prop and use the same way you would use a component.
function General(props) {
...
return (<props.substitute a={A} b={B} />);
}
function SpecificA(props) { ... }
function SpecificB(props) { ... }
<General substitute=SpecificA />
<General substitute=SpecificB />
score:0
Let's create a Wrapper Component:
export const Wrapper = (props) => {
return(<>
<Menu />
{props.children}
<Footer />
</>
)
}
You can now enclose your new into an existing structure.
You will enclose the Component in a Route for example:
<Route path="/" element={<Wrapper><ExampleComponent /></Wrapper>} />
score:2
Here is an example of a parent List react component and whos props contain a react element. In this case, just a single Link react component is passed in (as seen in the dom render).
class Link extends React.Component {
constructor(props){
super(props);
}
render(){
return (
<div>
<p>{this.props.name}</p>
</div>
);
}
}
class List extends React.Component {
render(){
return(
<div>
{this.props.element}
{this.props.element}
</div>
);
}
}
ReactDOM.render(
<List element = {<Link name = "working"/>}/>,
document.getElementById('root')
);
score:3
Late to the game, but here's a powerful HOC pattern for overriding a component by providing it as a prop. It's simple and elegant.
Suppose MyComponent
renders a fictional A
component but you want to allow for a custom override of A
, in this example B
, which wraps A
in a <div>...</div>
and also appends "!" to the text prop:
import A from 'fictional-tooltip';
const MyComponent = props => (
<props.A text="World">Hello</props.A>
);
MyComponent.defaultProps = { A };
const B = props => (
<div><A {...props} text={props.text + '!'}></div>
);
ReactDOM.render(<MyComponent A={B}/>);
score:3
Actually, your question is how to write a Higher Order Component (HOC). The main goal of using HOC is preventing copy-pasting. You can write your HOC as a purely functional component or as a class here is an example:
class Child extends Component {
render() {
return (
<div>
Child
</div>
);
}
}
If you want to write your parent component as a class-based component:
class Parent extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
If you want to write your parent as a functional component:
const Parent=props=>{
return(
<div>
{props.children}
</div>
)
}
score:6
You can pass in a component via. the props and render it with interpolation.
var DivWrapper = React.createClass({
render: function() {
return <div>{ this.props.child }</div>;
}
});
You would then pass in a prop
called child
, which would be a React component.
score:9
i prefer using React built-in API:
import React, {cloneElement, Component} from "react";
import PropTypes from "prop-types";
export class Test extends Component {
render() {
const {children, wrapper} = this.props;
return (
cloneElement(wrapper, {
...wrapper.props,
children
})
);
}
}
Test.propTypes = {
wrapper: PropTypes.element,
// ... other props
};
Test.defaultProps = {
wrapper: <div/>,
// ... other props
};
then you can replace the wrapper div with what ever you want:
<Test wrapper={<span className="LOL"/>}>
<div>child1</div>
<div>child2</div>
</Test>
score:14
Facebook recommends stateless component usage Source: https://web.archive.org/web/20160608001717/http://facebook.github.io/react/docs/reusable-components.html
In an ideal world, most of your components would be stateless functions because in the future we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations. This is the recommended pattern, when possible.
function Label(props){
return <span>{props.label}</span>;
}
function Hello(props){
return <div>{props.label}{props.name}</div>;
}
var hello = Hello({name:"Joe", label:Label({label:"I am "})});
ReactDOM.render(hello,mountNode);
score:30
You can pass it as a normal prop: foo={<ComponentOne />}
For example:
const ComponentOne = () => <div>Hello world!</div>
const ComponentTwo = () => (
<div>
<div>Hola el mundo!</div>
<ComponentThree foo={<ComponentOne />} />
</div>
)
const ComponentThree = ({ foo }) => <div>{foo}</div>
score:34
const ParentComponent = (props) => {
return(
{props.childComponent}
//...additional JSX...
)
}
//import component
import MyComponent from //...where ever
//place in var
const myComponent = <MyComponent />
//pass as prop
<ParentComponent childComponent={myComponent} />
score:138
Note I provided a more in-depth answer here
Runtime wrapper:
It's the most idiomatic way.
const Wrapper = ({children}) => (
<div>
<div>header</div>
<div>{children}</div>
<div>footer</div>
</div>
);
const App = () => <div>Hello</div>;
const WrappedApp = () => (
<Wrapper>
<App/>
</Wrapper>
);
Note that children
is a "special prop" in React, and the example above is syntactic sugar and is (almost) equivalent to <Wrapper children={<App/>}/>
Initialization wrapper / HOC
You can use an Higher Order Component (HOC). They have been added to the official doc recently.
// Signature may look fancy but it's just
// a function that takes a component and returns a new component
const wrapHOC = (WrappedComponent) => (props) => (
<div>
<div>header</div>
<div><WrappedComponent {...props}/></div>
<div>footer</div>
</div>
)
const App = () => <div>Hello</div>;
const WrappedApp = wrapHOC(App);
This can lead to (little) better performances because the wrapper component can short-circuit the rendering one step ahead with shouldComponentUpdate, while in the case of a runtime wrapper, the children prop is likely to always be a different ReactElement and cause re-renders even if your components extend PureComponent.
Notice that connect
of Redux used to be a runtime wrapper but was changed to an HOC because it permits to avoid useless re-renders if you use the pure
option (which is true by default)
You should never call an HOC during the render phase because creating React components can be expensive. You should rather call these wrappers at initialization.
Note that when using functional components like above, the HOC version do not provide any useful optimisation because stateless functional components do not implement shouldComponentUpdate
More explanations here: https://stackoverflow.com/a/31564812/82609
Source: stackoverflow.com
Related Query
- How to pass in a react component into another react component to transclude the first component's content?
- How to take the input from a react component and pass the length of the input to another react component
- How can I redirect to another component in react and pass the state that I set in the previous component?
- How to pass a function into another component in react
- How can I pass the children of a function component to another function component in a react class?
- how to pass the data from one component to another in react js
- How to pass data to another component not in the URL with React Router
- How do i pass the props to another component via react router?
- How do I pass the properties from one component to another in React
- React/Mobx: How to pass single item from a mapped array into another component and retrieve only the item associated with the value clicked
- React - how to pass state to another component
- Is there a right way to pass data into a React component from the HTML page?
- Making an HTML string from a React component in background, how to use the string by dangerouslySetInnerHTML in another React component
- How to pass a state className variable to another component in react
- How to pass the match when using render in Route component from react router (v4)
- How to update the state of a sibling component from another sibling or imported component in REACT
- How do you dynamically insert a React component into the DOM (for instance a dialog)?
- How to pass data from one component to another in React or React-Redux?
- How to pass server data into React component
- How to access state of one component into another component in react
- How do I pass in the variant property of the material-ui TextField from a wrapping React component
- I can not get the state from react router Link component using useLocation. So how can I pass it?
- How to pass graphQL query variable into a decorated react component
- How to pass a wrapped component into React Router without it constantly remounting
- how to get a Component variable from another component but their both in the same file React
- How to pass react hook state to another component for each click
- How to pass input values from a child Form component to the state of its parent component for submission with react hooks?
- How can I update component in React after adding a new item into the database, using react hooks?
- In React How to pass Id to another page class component
- How to pass a state to a Parent component if I have a button triggering the state in the 2nd Child in React
More Query from same tag
- What is a better way for ReactJS component reuse?
- promise chaining reject
- How to append a word 'COPY' into reducer state in react?
- fetch data react .map is not a function
- retrieve property value from state react redux
- When Reactjs has functional component as parent and child component as class
- Change state with dropdown reactstrap
- How do I deploy my react app to GitHub Pages in production mode?
- PayFast payment integration in ReactJS
- Showing number of entries needed in antd table in react JS
- Refactoring dropdown list
- ReactJS+ Antd - pagination dynamic row expand issue
- Autoplay is removed from HTML after rendering
- How to use VideoJS plugins with ReactJS?
- Selecting input element form of a react functional component
- How do i hookup a React button to authenticate with Devise Token Auth + OmniAuth
- Redirect to another route after submission success
- Module Not Found Error while Pushing to Heroku
- How can I store my JWT token in userInfo?
- React mutate state before passing props
- How to solve the network error on axios api call?
- Dynamic HTML lang property in statically generated Next.js pages
- Javascript : How to get the key value json format in an array
- value becomes undefined because of setState
- Imported Variable not translated
- React Form using Winterfell
- How to call a class and setState in one onClick(ReactJS)
- React: Do not render menu based on child component state
- Render html div in react
- TypeError: Class constructor ESLintWebpackPlugin cannot be invoked without 'new'