Nextjs/Reactjs: How to create Templates— The Pixels
This article will show a solution to create Templates separated from Logic codes in a Nextjs/Reactjs project.
What is Nextjs/Reactjs?
Reactjs is a JavaScript library for building user interfaces.
Nextjs supports SSR (Server side rendering) feature.
The Pixels
I am building a Javascript framework — “The Pixels” based on Nextjs and Reactjs.
The Pixels will be help developers build apps faster and easier. The first feature is Templates.
Templates
A Reactjs project has three important parts: Logical state, View state and User interface.
Without Templates we maybe code all things in a single file. Logical codes, View codes and User interface html elements (JSX) mixed in a file. It’s very difficult to handle codes this way.
//file: a.com.tsx
class AComponent extends React.Component { handleUserAction = () => { ///Very complicated codes… //Update state
this.setState({a,b}) } render() { ///Very complicated codes
const {a, b} = this.state
const {x, y} = this.props
return (
<section>
<div className=”content”>…{a}{b}{x}{y}..</div>
</section>
)
}
}
Templates will help us separate User interface code and Logical codes/View codes.
//File: a.com.tsx
import {Component} from <Pixels Core>
import {ATemplate} from “./a.tpl.tsx”class AComponent extends Component {
template = ATemplate handleUserAction = () => {
///Very complicated codes… //Update state
this.setState({a,b})
}
///View: Just return formatted data view() {
///Very complicated codes
const {a, b} = this.state
const {x, y} = this.props
return {a, b, x, y}
}
}
File template: a.tpl.tsx:
//File: a.tpl.tsx
import {ITemplate} from <Pixels Core>//self is this in AComponent
const ATemplate: ITemplate = ({ a, b, x, y}, self: Object) => { return (
<section>
<div className=”content”>…{a}{b}{x}{y}..</div>
</section>
)
}
How can we do this?
This is The Pixels core inside:
Interface ITemplate
type ITemplate = (params: any, self: Object) => ReactNode
Core Component
abstract class Component<P = any, S = any, SS = any> extends React.Component<P, S, SS> { //Template
abstract template: ITemplate
//view: return formatted data will be passed to template
abstract view(): any
//render: return user interface, override from Reactjs
render(): React.ReactNode { const formattedData = this.view();
return this.template(formattedData, this); }
}
Conclusions
I think Templates help us to handle codes more efficient. It’s easy to read, easy to debug and easy to upgrade.
Pixels framework git: https://gitlab.com/mrbaobao/pixels-framework.