plotly / react-cytoscapejs

React component for Cytoscape.js network visualisations
MIT License
472 stars 69 forks source link

How to get cy ref with typescript? #58

Open tunesmith opened 4 years ago

tunesmith commented 4 years ago

The docs indicate this technique for straight jsx:

class MyApp extends React.Component {
  render() {
    return <CytoscapeComponent cy={(cy) => { this.cy = cy }}>;
  }
}

When I change my component to *.tsx, I get errors like TS2339: Property 'cy' does not exist on type 'MyApp'.

How can this be adapted so typescript won't complain for the class component?

tunesmith commented 4 years ago

This ended up easier than I expected - adding a cy = null; above the render() method cleared the error, although there is probably a better way to make it more idiomatic typescript.

agonzalezjr commented 3 years ago

If using hooks / functional component, this seems to work:

export const Chart = (props: any): ReactElement => {
  const cyRef = useRef<Cytoscape.Core>();

  ...

  return (
    <CytoscapeComponent
      cy={(cy): void => {
        cyRef.current = cy;
      }}
      elements={elements}
      ...
    />
  );