Skip to main content

How to access Gantt API

You can use either of the two ways below to get access to the Gantt API:

  • apply the init handler function with api as the parameter
  • pass a state setter to the ref prop to store the api object in a state variable (please, refer to useState)

Apply the init handler​

You can access Gantt API using the init handler function that takes api as the parameter.

The example below shows how to use the init function and output to the console the current zoom level by listening to the zoom-scale action with the help of the api.on() method and getting the state of the zoom level via the api.getState() method.

Example:

import { getData } from "../data";
import { Gantt } from "@svar-ui/react-gantt";

const data = getData();

const init = (api) => {
api.on("zoom-scale", () => {
console.log("The current zoom level is", api.getState().zoom);
});
};

export default function App() {
return (
<>
<h4>Point over Gantt chart, then hold Ctrl and use mouse wheel to zoom</h4>
<Gantt init={init} tasks={data.tasks} links={data.links} zoom />
</>
);
}

Bind to api​

You can access Gantt API via the api gateway object.

In the example below we store the Gantt api in a state variable via ref={setApi} and pass the api variable to the Toolbar. When Gantt mounts, the state update re-renders the component, so Toolbar receives the api:

import { useState } from "react";
import { getData } from "./common/data";
import { Gantt, Toolbar } from "@svar-ui/react-gantt";

const data = getData();

export default function App() {
const [api, setApi] = useState(null);

return (
<>
<Toolbar api={api} />
<Gantt tasks={data.tasks} ref={setApi} />
</>
);
}

Components that cannot render without the api, such as Editor and ResourceLoad, should be rendered only after the api is available:

{api && <Editor api={api} />}
note

If you need the api only inside event handlers, you can keep it in a useRef variable and call apiRef.current.exec(...) in the handler. Do not pass apiRef.current as a prop: it is null during the first render, and React does not re-render the component when the ref is filled.

api methods​

See each method description in the next sections.