Reputation: 819
I have a situation where I want to render a different header depending on the value of a variable in a Redux State.
This is my MyClass.js
class MyClass extends React.Component {
constructor(props) {
this.state = {
headerState: "home"
};
this.GetHeader = this.GetHeader.bind(this);
}
GetHeader() {
const headerType = this.renderHeader;
if (headerType == "a") {
return (Some html code);
} [...] {
return (Some html code);
} else {
return (Some html code);
}
}
render() { <
GetHeader / > // This is line 79
}
function mapStateToProps(state, ownProps) {
return {
renderHeader: state.renderHeader
};
}
}
export default withRouter(connect(mapStateToProps)(MyClass));
This is my reducer:
export default function renderHeaderReducer(state = [], action) {
switch(action.type) {
case 'RENDER_HEADER':
return [...state, Object.assign({}, action.headerType)];
default:
return state;
}
}
When I tried running the code, on the browser it says:
Uncaught ReferenceError: GetHeader is not defined at Header.render (Header.js:79).
I followed this doc(first example)
Not sure what I am doing wrong or what concepts I must have misunderstood in terms of binding methods to this
context. Cheers.
Upvotes: 1
Views: 490
Reputation: 222538
There's no GetHeader
variable, it's this.GetHeader
method. There are no reasons to use GetHeader
as React element, it's a method that doesn't need its own props. It doesn't need to be bound to this
when called as a method.
There's no this.renderHeader
because renderHeader
is a prop.
It likely should be:
state = {
headerState: "home"
}
GetHeader() {
const headerType = this.props.renderHeader;
if (headerType == "a") {
return (Some html code);
} [...] {
return (Some html code);
} else {
return (Some html code);
}
}
render() {
return <>
{this.GetHeader()}
...
</>;
}
If render
isn't too big or GetHeader
isn't reused, there may be no need to extract its contents from render
.
Upvotes: 2
Reputation: 357
Because you are missing function in front of GetHeader() {
function GetHeader(){}
For more reference check : https://reactjs.org/docs/conditional-rendering.html
Upvotes: 0
Reputation: 14385
Because it isn't. You should add a variable in the render:
render() {
const GetHeader = this.GetHeader;
return <GetHeader />;
}
You code had 2 issues: 1. The GetHeader wasn't accessible locally. 2. You didn't use return statement
Upvotes: 0