React
This document shows you how to create a Family Tree JS 2 React project.
Using an NPM React project
- Create a new project:
bash
npx create-react-app familytree- Go to the project root folder:
bash
cd familytree- Install Family Tree JS 2.
Add the extracted familytree2.js file to your src folder.
If you use TypeScript, add this line at the end of both the
.jsand.d.tsfiles:typescriptexport default FamilyTree;and Copy the
.d.tsfile into the same folder as well.
- Create mytree.js in the src folder with the following content:
javascript
import React, { Component } from 'react';
import FamilyTree from './familytree2.js';
export default class Tree extends Component {
constructor(props) {
super(props);
this.divRef = React.createRef();
}
shouldComponentUpdate() {
return false;
}
componentDidMount() {
this.familyTree = new FamilyTree(this.divRef.current);
this.familyTree.readOnly = false;
this.familyTree.addFamilyMembers(this.props.nodes).draw(1);
}
render() {
return <div id="tree" ref={this.divRef}></div>;
}
}- Change App.js as follows:
javascript
import React, { Component } from 'react';
import Tree from './mytree';
export default class App extends Component {
render() {
return (
<div style={{ height: '100%' }}>
<Tree
nodes={[
{ id: 1, spouseIds: [2], motherId: 3, fatherId: 4 },
{ id: 2 },
{ id: 3 },
{ id: 4 }
]}
/>
</div>
);
}
}- Add this CSS to index.css:
css
html, body, #root, #tree {
height: 100%;
}- Start the project:
bash
npm start