I’ve created this demo to show the use of class-based React components in a Frontity project and how you can access the state from within a class-based component.
Usually when working with Frontity, or any modern React-based framework, you would use function-based React components.
The demo is based on the standard mars-theme
. The differences are:
-
There’s a new route added to the menu in frontity.settings.js
(lines 36 - 39) for testing the new class-based component.
-
A new property state.theme.ccString
has been added to index.js
(line 23), which will be used later to demonstrate how we can access properties in the state from within the class-based component.
-
A new file class-component.js
contains a new component created as a class-based component rather than a function-based component. Note that:
a. You need to import React
(line 1);
b. Class-based components must have a render()
function;
c. You need to import the HOC connect
(line 2) and connect the class-based component to the state (line 16) when exporting it;
d. You can then access properties in the state using this.props
within the class-based component (line 9 accesses state.router.link
and line 10 accesses state.theme.ccString
, the custom property we added above ).
-
The class-based component is imported normally into index.js
(line 9) and then rendered depending on the value of state.router.link
(line 44).
Here, for convenient reference, is the code for the class-based component used in the demo:
import React from 'react'
import { connect } from 'frontity'
class ClassComponent extends React.Component {
render() {
return (
<>
<h2>This page is rendered by a class-based component</h2>
<p><em>Current path:</em> {this.props.state.router.link}</p>
<p><em>Value of 'state.theme.ccString':</em> {this.props.state.theme.ccString}</p>
</>
)
}
}
export default connect(ClassComponent)