I am trying to change views dynamically based on user click
I understand why the component does not re-render, but I cannot see how to best make re-render without force update function.
I dont think I can useState since it will be outside of function component.
Have the following code in Structure.ts:
import React from 'react'
export class Node {
private _nodeName : string;
private _reactElement: JSX.Element;
constructor(nodeName:string, reactElement:JSX.Element){
this._nodeName = nodeName;
this._reactElement = reactElement;
}
public render(){
return this._reactElement;
}
}
export class ViewStructure{
private _viewNodeList: Node[] =[];
private _currentViewNode: Node;
public setNode(index:number){
}
public next(){
debugger;
let currentNodeIndex = this._viewNodeList.findIndex((node) => node === this._currentViewNode);
let nextNodeIndex = currentNodeIndex +1;
this._currentViewNode = this._viewNodeList[nextNodeIndex];
}
public previous(){
console.log('cicked previous')
}
public addNode(viewNode:Node){
if(!this._currentViewNode){
this._currentViewNode = viewNode;
}
this._viewNodeList.push(viewNode);
}
public render(){
return this._currentViewNode.render();
}
}
and main react component App.tsx
import React, {useState, useRef, useEffect} from 'react'
import { ViewNode, ViewStructure } from "./Structure";
import SomeComponent from './SomeComponent';
import SomeComponent2 from './SomeComponent2';
export default function App() {
var NodeViewStructure = new ViewStructure();
var personalInfo = new ViewNode("Screen2", <SomeComponent2 ></SomeComponent2> );
var intro = new ViewNode('Screen 1', <SomeComponent name="John" age={22}></SomeComponent> );
NodeViewStructure.addNode(intro);
NodeViewStructure.addNode(personalInfo);
useEffect(()=>{
console.log('just rendered');
debugger;
}, [])
function nextView(){
console.log('next');
debugger;
NodeViewStructure.next();
}
return (
<div className="App">
<span > {NodeViewStructure.render()} </span>
<button onClick={() =>nextView()}>Next </button>
</div>
);
}