Skip to content

React

This document shows you how to create a Family Tree JS 2 React project.

Using an NPM React project

  1. Create a new project:
bash
npx create-react-app familytree
  1. Go to the project root folder:
bash
cd familytree
  1. Install Family Tree JS 2.
  • Download the package.

  • Add the extracted familytree2.js file to your src folder.

  • If you use TypeScript, add this line at the end of both the .js and .d.ts files:

    typescript
    export default FamilyTree;

    and Copy the .d.ts file into the same folder as well.

  1. 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>;
  }
}
  1. 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>
    );
  }
}
  1. Add this CSS to index.css:
css
html, body, #root, #tree {
  height: 100%;
}
  1. Start the project:
bash
npm start