Can I Pass Component State To Hoc?
Is there any way to send data from the component's state to HoC? My component My HoC component: Is there any way to do this? Is the only option is to provide props that must com
Solution 1:
importReact, { Component } from'react';
import withHandleError from'./withHandleError';
classSendScreenextendsComponent {
contructor() {
super();
this.state = {
error: true
}
}
render() {
return (
<divstate={...this.state}> Test </div>
)
}
};
exportdefaultwithHandleError(SendScreen)
You can pass the state as a prop in your component.
Solution 2:
A parent isn't aware of child's state. While it can get an instance of a child with a ref and access state
, it can't watch on state updates, the necessity to do this indicates design problem.
This is the case for lifting up the state. A parent needs to be notified that there was an error:
export default Cmp => {
returnclassextendsComponent{
this.state = {
error: false
}
onError() = () => this.setState({ error: true });
render() {
if (error) {
return <ErrorScreen />
}
return <Cmp onError={this.onError} { ...this.props } />
}
}
}
Solution 3:
export default withHandleError(data)(SendScreen)
In data you can send the value you want to pass to HOC, and can access as prop.
Solution 4:
I know I answer late, but my answer can help other people
It is very easy to do.
- WrappedComponent
importReact, {Component} from'react';
importPropTypesfrom'prop-types';
importHocComponentfrom'./HocComponent';
const propTypes = {
passToHOC: PropTypes.func,
};
classWrappedComponentextendsComponent {
constructor(props) {
super(props);
this.state = {
error: true,
};
}
componentDidMount() {
const {passToHOC} = this.props;
const {error} = this.state;
passToHOC(error); // <--- pass the <<error>> to the HOC component
}
render() {
return<div> Test </div>;
}
}
WrappedComponent.propTypes = propTypes;
exportdefaultHocComponent(WrappedComponent);
- HOC Component
importReact, {Component} from'react';
exportdefaultWrappedComponent => {
returnclassextendsComponent {
constructor() {
super();
this.state = {
error: false,
};
}
doAnything = error => {
console.log(error); //<-- <<error === true>> from child componentthis.setState({error});
};
render() {
const {error} = this.state;
if (error) {
return<div> ***error*** passed successfully</div>;
}
return<WrappedComponent {...this.props} passToHOC={this.doAnything} />;
}
};
};
Post a Comment for "Can I Pass Component State To Hoc?"