### Installation Command
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Use this command to install the react-cytoscapejs library.
```bash
npm install react-cytoscapejs --save
```
--------------------------------
### Install react-cytoscapejs with npm
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Install the react-cytoscapejs package and a specific version of cytoscape using npm.
```bash
npm install react-cytoscapejs
npm install cytoscape@3.x.y # your desired version, 3.2.19 or newer
```
--------------------------------
### Install react-cytoscapejs with yarn
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Install the react-cytoscapejs package and a specific version of cytoscape using yarn.
```bash
yarn add react-cytoscapejs
yarn add cytoscape@3.x.y # your desired version, 3.2.19 or newer
```
--------------------------------
### Install react-cytoscapejs and Cytoscape
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/README.md
Install the necessary packages using npm. Ensure you are using a compatible version of Cytoscape (e.g., 3.x.y).
```bash
npm install react-cytoscapejs cytoscape@3.x.y
```
--------------------------------
### Component Initialization
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Basic example of initializing the CytoscapeComponent.
```jsx
import CytoscapeComponent from 'react-cytoscapejs';
const cytoElements = [
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Edge 1' } }
];
const App = () => (
);
```
--------------------------------
### MyApp Component Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/CytoscapeComponent.md
Example of a basic React component structure that might include CytoscapeComponent.
```javascript
class MyApp extends React.Component {
constructor(props) {
super(props);
}
// ...
}
```
--------------------------------
### Event Handling Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Shows how to handle node click events.
```jsx
import CytoscapeComponent from 'react-cytoscapejs';
const cytoElements = [
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Edge 1' } }
];
const App = () => (
{
cy.on('tap', 'node', (evt) => {
console.log('Tapped ' + evt.target.id());
});
}}
/>
);
```
--------------------------------
### Internal Component Update Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/patching.md
This example shows how the patch function is called internally by a component during mounting and updating. It's not typically called directly by users.
```javascript
// Called automatically in componentDidMount and componentDidUpdate
this.updateCytoscape(null, this.props);
// Which internally calls:
patch(cy, prevProps, newProps, diff, toJson, get, forEach);
```
--------------------------------
### Error Handling Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Illustrates basic error handling for component initialization.
```jsx
import CytoscapeComponent from 'react-cytoscapejs';
const cytoElements = [
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Edge 1' } }
];
const App = () => (
);
```
--------------------------------
### Prop Usage Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Demonstrates how to use various props for CytoscapeComponent.
```jsx
import CytoscapeComponent from 'react-cytoscapejs';
const cytoElements = [
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Edge 1' } }
];
const App = () => (
);
```
--------------------------------
### Install react-cytoscapejs and Cytoscape.js
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/quick-start.md
Install the react-cytoscapejs component and a compatible Cytoscape.js version using npm or yarn. Ensure Cytoscape.js is version 3.2.19 or newer.
```bash
npm install react-cytoscapejs cytoscape@3.x.y
```
```bash
yarn add react-cytoscapejs cytoscape@3.x.y
```
--------------------------------
### Minimal react-cytoscapejs Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/quick-start.md
A basic React component demonstrating how to render a Cytoscape graph with nodes and an edge. This example sets up the necessary elements and renders them within a specified size.
```javascript
import React from 'react';
import CytoscapeComponent from 'react-cytoscapejs';
class MyApp extends React.Component {
render() {
const elements = [
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Connection' } }
];
return (
);
}
}
export default MyApp;
```
--------------------------------
### CytoscapeComponent render example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/CytoscapeComponent.md
This example shows the structure of the div element returned by the render method. It includes common attributes like id, className, and style.
```javascript
// Automatically called by React during render phase
// Returns:
```
--------------------------------
### Access Cytoscape Instance and Control Zoom
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/quick-start.md
Get the Cytoscape instance using the 'cy' prop to programmatically control graph features like zoom. This example shows how to attach the instance and trigger a zoom action.
```javascript
class MyApp extends React.Component {
constructor(props) {
super(props);
this.cy = null;
}
handleZoom = () => {
this.cy.zoom(2);
}
render() {
return (
<>
{ this.cy = cy; }}
/>
>
);
}
}
```
--------------------------------
### Hash-Based Object Difference Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/diff-and-json.md
Demonstrates the usage of hashDiff with pseudo-code for objects implementing a hash method.
```javascript
// Pseudo-code for object with hash method
const obj1 = {
data: [1, 2, 3],
hash: function() { return 'hash1'; }
};
const obj2 = {
data: [1, 2, 3],
hash: function() { return 'hash1'; }
};
hashDiff(obj1, obj2) // false (same hash)
```
--------------------------------
### Programmatic Graph Interaction Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/types.md
Use the `cy` reference within the callback prop to interact with the Cytoscape graph programmatically. This example demonstrates attaching event listeners and logging node count.
```javascript
{
// Use cy reference for programmatic access
cy.on('tap', 'node', (event) => {
console.log('Tapped node:', event.target.id());
});
const nodeCount = cy.nodes().length;
console.log('Graph has', nodeCount, 'nodes');
}}
/>
```
--------------------------------
### Basic Usage of react-cytoscapejs
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/CytoscapeComponent.md
This example demonstrates how to use the CytoscapeComponent in a React application. It includes defining elements, stylesheets, and layout for the graph, and setting up a callback for the Cytoscape instance.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import CytoscapeComponent from 'react-cytoscapejs';
class MyApp extends React.Component {
render() {
const elements = [
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Edge 1→2' } }
];
const stylesheet = [
{
selector: 'node',
style: {
'width': 30,
'height': 30,
'background-color': '#555',
'label': 'data(label)'
}
},
{
selector: 'edge',
style: {
'width': 2,
'line-color': '#ccc'
}
}
];
const layout = { name: 'grid' };
return (
{ this.cy = cy; }}
/>
);
}
}
ReactDOM.render(React.createElement(MyApp), document.getElementById('root'));
```
--------------------------------
### Shallow Object Difference Examples
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/diff-and-json.md
Illustrates the behavior of shallowObjDiff with primitives, null/undefined values, object references, and object properties.
```javascript
// Primitives
shallowObjDiff(5, 5) // false
shallowObjDiff(5, 6) // true
shallowObjDiff('hello', 'hello') // false
// Null/undefined
shallowObjDiff(null, null) // false
shallowObjDiff(null, undefined) // false (both null-ish)
shallowObjDiff(null, 5) // true (one is null-ish)
// References
const obj = { a: 1 };
shallowObjDiff(obj, obj) // false (same reference)
// Object properties
shallowObjDiff({a: 1}, {a: 1}) // false (same properties)
shallowObjDiff({a: 1}, {a: 2}) // true (different values)
shallowObjDiff({a: 1}, {a: 1, b: 2}) // true (different key count)
// Nested objects (shallow - only top level)
shallowObjDiff({x: {a: 1}}, {x: {a: 1}}) // true (different nested object references)
shallowObjDiff({x: {a: 1}}, {x: {a: 1}}) // false if same reference to nested object
```
--------------------------------
### Default get function for object properties
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
The default 'get' function simply accesses properties using bracket notation.
```javascript
const get = (object, key) => object[key];
```
--------------------------------
### Advanced Pattern: Dynamic Updates
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Example of dynamically updating graph elements.
```jsx
import CytoscapeComponent from 'react-cytoscapejs';
import React, { useState } from 'react';
const App = () => {
const [elements, setElements] = useState([
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Edge 1' } }
]);
const addNode = () => {
const newNodeId = `node_${elements.length + 1}`;
setElements(prevElements => [
...prevElements,
{ data: { id: newNodeId, label: `Node ${elements.length + 1}` }, position: { x: Math.random() * 200, y: Math.random() * 200 } }
]);
};
return (
);
};
export default App;
```
--------------------------------
### Using Immutable.js for Efficient Updates
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/configuration.md
Integrates Immutable.js for managing graph elements, providing efficient updates and state management. Requires Immutable.js to be installed.
```javascript
import Immutable from 'immutable';
const get = (object, key) => {
if (Immutable.Map.isMap(object) || Immutable.List.isList(object)) {
return object.get(key);
}
return object[key];
};
const toJson = (object) => {
if (Immutable.isImmutable(object)) {
return object.toJSON();
}
return object;
};
const diff = (objectA, objectB) => objectA !== objectB;
const forEach = (list, iterator) => list.forEach(iterator);
```
--------------------------------
### Default get Function Implementation
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/types.md
The default implementation for the get function accesses a property from an object. It returns null if the object is null or undefined.
```javascript
const get = (obj, key) => obj != null ? obj[key] : null;
```
--------------------------------
### Custom Diff and JSON Utilities with Immutable.js
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/diff-and-json.md
Shows how to implement custom get, toJson, diff, and forEach functions to work with Immutable.js data structures within a CytoscapeComponent.
```javascript
import Immutable from 'immutable';
import CytoscapeComponent from 'react-cytoscapejs';
const customGet = (object, key) => {
if (Immutable.Map.isMap(object) || Immutable.List.isList(object)) {
return object.get(key);
}
return object[key];
};
const customToJson = (object) => {
if (Immutable.isImmutable(object)) {
return object.toJSON();
}
return object;
};
const customDiff = (objectA, objectB) => objectA !== objectB;
const customForEach = (list, iterator) => list.forEach(iterator);
```
--------------------------------
### Styling Nodes and Edges in React
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/README.md
Define and apply custom stylesheets to nodes and edges for visual customization. This example demonstrates styling for default states, selected nodes, and edges.
```javascript
const stylesheet = [
{
selector: 'node',
style: {
'width': 40,
'height': 40,
'background-color': '#555',
'label': 'data(label)',
'text-valign': 'center'
}
},
{
selector: 'node:selected',
style: {
'background-color': '#0066cc'
}
},
{
selector: 'edge',
style: {
'width': 2,
'line-color': '#999',
'target-arrow-color': '#999',
'target-arrow-shape': 'triangle'
}
}
];
```
--------------------------------
### Apply Layout to CytoscapeComponent
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/quick-start.md
Configure node positioning using built-in layout algorithms like 'grid', 'random', or 'cose'. For advanced layouts, install and register extensions.
```javascript
```
```javascript
import Cytoscape from 'cytoscape';
import COSEBilkent from 'cytoscape-cose-bilkent';
Cytoscape.use(COSEBilkent);
```
--------------------------------
### get()
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/diff-and-json.md
Safely retrieves a value from an object or array at a specified key. It handles null or undefined objects gracefully, returning null in such cases.
```APIDOC
## get()
### Description
Gets a value from an object or array at the specified key. Handles null/undefined safely.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Method Signature
`function get(obj: any, key: string | number): any`
### Returns
`any` - The value at `obj[key]` or `null` if `obj` is null/undefined.
### Examples
```javascript
get({ a: 1, b: 2 }, 'a') // 1
get([10, 20, 30], 1) // 20
get(null, 'any') // null
get(undefined, 'any') // null
get({ data: { id: 'x' } }, 'data') // { id: 'x' }
```
```
--------------------------------
### React Component componentWillUnmount Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/lifecycle-and-patterns.md
This snippet illustrates the componentWillUnmount lifecycle method. It is invoked just before the component is unmounted, ensuring the Cytoscape instance is destroyed and resources are cleaned up.
```javascript
class MyApp extends React.Component {
componentWillUnmount() {
// Called when component is unmounting
// Cytoscape instance is destroyed automatically
}
render() {
return ;
}
}
```
--------------------------------
### Custom Diff Function Examples
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/patching.md
Illustrates two custom diff functions: a shallow property comparison and a reference equality check. The reference equality check is significantly faster for immutable objects.
```javascript
// Shallow diff - checks all properties
const diff = (a, b) => {
// ... property-by-property comparison
};
```
```javascript
// Reference equality - much faster for Immutable objects
const diff = (a, b) => a !== b;
```
--------------------------------
### Access to Cytoscape Instance
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/lifecycle-and-patterns.md
Use the `cy` prop to get a reference to the Cytoscape instance for advanced programmatic control, such as fitting the view or zooming.
```APIDOC
## Access to Cytoscape Instance
### Description
Use the `cy` prop to get a reference to the Cytoscape instance for advanced programmatic control, such as fitting the view or zooming.
### Method
Callback function provided to the `cy` prop.
### Parameters
- **cy** (Cytoscape.Core) - The Cytoscape instance.
### Example:
```javascript
class MyApp extends React.Component {
constructor(props) {
super(props);
this.cy = null;
}
handleFit = () => {
if (this.cy) {
this.cy.fit();
}
}
handleZoom = (factor) => {
if (this.cy) {
this.cy.zoom(this.cy.zoom() * factor);
}
}
render() {
return (
<>
{ this.cy = cy; }}
/>
>
);
}
}
```
```
--------------------------------
### Minimal Cytoscape.js React Component Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/README.md
A basic React component demonstrating how to render a Cytoscape graph using react-cytoscapejs. It defines nodes and edges and applies basic styling for dimensions.
```javascript
import React from 'react';
import CytoscapeComponent from 'react-cytoscapejs';
class App extends React.Component {
render() {
const elements = [
{ data: { id: 'one' }, position: { x: 0, y: 0 } },
{ data: { id: 'two' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two' } }
];
return (
);
}
}
export default App;
```
--------------------------------
### Provide Custom Data Structures
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/INDEX.md
Supply custom implementations for utility functions like `get`, `toJson`, `diff`, and `forEach` to customize data handling. These props accept functions from external modules or custom-defined ones.
```javascript
```
--------------------------------
### Using Immutable.js with Cytoscape.js
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/README.md
Integrate Immutable.js with Cytoscape.js for efficient state management. This example provides helper functions for accessing and converting Immutable data structures.
```javascript
import Immutable from 'immutable';
const get = (obj, key) => {
if (Immutable.Map.isMap(obj) || Immutable.List.isList(obj)) {
return obj.get(key);
}
return obj[key];
};
const toJson = (obj) => Immutable.isImmutable(obj) ? obj.toJSON() : obj;
const diff = (a, b) => a !== b;
const forEach = (list, fn) => list.forEach(fn);
```
--------------------------------
### Get Cytoscape Instance Reference
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Use the `cy` prop to obtain a reference to the Cytoscape instance for direct manipulation or querying.
```jsx
{ myCyRef = cy }} />
```
--------------------------------
### Custom forEach function for list iteration
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Implement a custom 'forEach' function to iterate over list elements. This example shows the implementation for both Immutable.js Lists and standard JavaScript arrays.
```javascript
const forEach = (list, iterator) => list.forEach(iterator); // same for immutable and js arrays
```
--------------------------------
### React Component componentDidMount Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/lifecycle-and-patterns.md
This snippet shows the componentDidMount lifecycle method in a React component. It is invoked after the component is mounted to the DOM, at which point the Cytoscape instance is created.
```javascript
class MyApp extends React.Component {
componentDidMount() {
// Called after component is mounted
// Cytoscape instance is now created
}
render() {
return ;
}
}
```
--------------------------------
### Custom get function for object properties
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Implement a custom 'get' function to retrieve properties from objects, supporting both standard JavaScript objects and Immutable.js Maps/Lists.
```javascript
const get = (object, key) => {
// must check type because some props may be immutable and others may not be
if (Immutable.Map.isMap(object) || Immutable.List.isList(object)) {
return object.get(key);
} else {
return object[key];
}
}
```
--------------------------------
### Immutable.js get Function Implementation
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/types.md
This implementation of the get function handles Immutable.js Maps and Lists by using their .get() method. For other types, it falls back to standard property access.
```javascript
const get = (object, key) => {
if (Immutable.Map.isMap(object) || Immutable.List.isList(object)) {
return object.get(key);
}
return object[key];
};
```
--------------------------------
### Default Diff and JSON Utilities
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/diff-and-json.md
Demonstrates the import and usage of default diff and JSON utilities within a component's defaults and update logic.
```javascript
import { shallowObjDiff } from './diff';
import { get, toJson, forEach } from './json';
export const defaults = {
diff: shallowObjDiff,
get,
toJson,
forEach,
// ... other defaults
};
```
```javascript
updateCytoscape(prevProps, newProps) {
const cy = this._cy;
const { diff, toJson, get, forEach } = newProps;
// Pass to patch function
patch(cy, prevProps, newProps, diff, toJson, get, forEach);
}
```
--------------------------------
### Error Handling in Event Listeners
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/lifecycle-and-patterns.md
Demonstrates how to safely set up event listeners within the `cy` callback to catch potential errors during initialization.
```javascript
{
try {
cy.on('tap', 'node', (event) => {
// Handle event
});
} catch (error) {
console.error('Error setting up event listeners:', error);
}
}}
/>
```
--------------------------------
### File Organization Structure
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/INDEX.md
Illustrates the directory structure of the react-cytoscapejs library, showing the location of key modules.
```tree
react-cytoscapejs/
├── src/
│ ├── index.js # Entry point (exports CytoscapeComponent)
│ ├── component.js # Main React component
│ ├── types.js # PropTypes definitions (in types.md)
│ ├── defaults.js # Default prop values (documented)
│ ├── patch.js # Prop change patching system (documented)
│ ├── diff.js # Difference functions (documented)
│ └── json.js # JSON utilities (documented)
```
--------------------------------
### Graph with Layout Algorithm
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/configuration.md
Applies a 'cose-bilkent' layout algorithm to arrange the graph elements. Requires the elements prop to be defined.
```javascript
```
--------------------------------
### Complete Custom Configuration
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/defaults.md
Provide a full custom configuration for elements, stylesheet, layout, zoom, pan, and interaction behaviors. Use this when you need complete control over the graph's appearance and functionality.
```javascript
```
--------------------------------
### Rendering Hints (Canvas Renderer)
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/CytoscapeComponent.md
Props to optimize rendering performance, especially for the canvas renderer.
```APIDOC
## Rendering Hints (Canvas Renderer)
### `headless`
- **Type**: Boolean
- **Default**: false
- **Description**: Whether the Cytoscape instance should render to the DOM. If true, rendering is skipped (immutable after initialization)
### `styleEnabled`
- **Type**: Boolean
- **Default**: false
- **Description**: Enable style functionality in headless instances. Has no effect on rendered instances
### `hideEdgesOnViewport`
- **Type**: Boolean
- **Default**: false
- **Description**: Hint to hide edges during zoom and pan operations for performance
### `textureOnViewport`
- **Type**: Boolean
- **Default**: false
- **Description**: Hint to use a preview texture during viewport changes
### `motionBlur`
- **Type**: Boolean
- **Default**: false
- **Description**: Hint to apply motion blur effect
### `motionBlurOpacity`
- **Type**: Number
- **Default**: undefined
- **Description**: Motion blur strength from 0 to 1 (larger = stronger effect)
### `wheelSensitivity`
- **Type**: Number
- **Default**: undefined
- **Description**: Multiplier for wheel zoom speed. Do not change unless using non-standard hardware
### `pixelRatio`
- **Type**: String | Number
- **Default**: undefined
- **Description**: The pixel ratio for rendering; can be `'auto'` or a positive number
```
--------------------------------
### Immutable.js List of Elements
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Example of defining graph elements using Immutable.js List and Map for efficient updates in React Cytoscape.js.
```javascript
const elements = Immutable.List([
Immutable.Map({ data: Immutable.Map({ id: 'foo', label: 'bar' }) })
]);
```
--------------------------------
### Default Property Access Function
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/defaults.md
Gets a value from an object at the specified key. Returns null if the object is null or undefined. Imported from src/json.js.
```javascript
const get = (obj, key) => (obj != null ? obj[key] : null);
```
--------------------------------
### Basic Graph with Custom Dimensions
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/configuration.md
Renders a simple graph with specified width and height. Ensure elements are correctly formatted.
```javascript
```
--------------------------------
### Safe Object/Array Access with get()
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/diff-and-json.md
Safely retrieves a value from an object or array using a key. Returns null if the object is null or undefined, preventing errors.
```javascript
const get = (obj, key) => (obj != null ? obj[key] : null);
```
```javascript
get({ a: 1, b: 2 }, 'a') // 1
get([10, 20, 30], 1) // 20
get(null, 'any') // null
get(undefined, 'any') // null
get({ data: { id: 'x' } }, 'data') // { id: 'x' }
```
```javascript
const get = (object, key) => {
if (Immutable.Map.isMap(object) || Immutable.List.isList(object)) {
return object.get(key);
}
return object[key];
};
```
--------------------------------
### CytoscapeComponent API
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Documentation for the main CytoscapeComponent, including its lifecycle methods, render method, static methods, and props.
```APIDOC
## CytoscapeComponent
### Description
The main component for integrating Cytoscape.js with React. It handles rendering the graph, managing its state, and providing lifecycle hooks.
### Class Definition
`CytoscapeComponent`
### Lifecycle Methods
- **mount**: Called when the component is first mounted.
- **update**: Called when the component's props or state change.
- **unmount**: Called when the component is removed from the DOM.
### render()
### Static Method: normalizeElements()
### Props
- **props**: Complete table of 30+ props available for configuration.
### Advanced Usage Examples
Includes examples for complex scenarios and integrations.
### Related Resources
Links to external resources and further reading.
```
--------------------------------
### Default Values API
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/MANIFEST.md
Reference for default configurations, including elements, stylesheet, zoom, pan, and default utility functions.
```APIDOC
## Default Values
### Description
Provides default configurations for elements, stylesheet, zoom, pan, and utility functions.
### Default Configurations
- **Default elements**: Initial graph elements.
- **Default stylesheet**: Base styling for the graph.
- **Default zoom**: Initial zoom level.
- **Default pan**: Initial pan position.
### Default Utility Functions
- **diff**: Default differencing utility.
- **get**: Default getter utility.
- **toJson**: Default JSON conversion utility.
- **forEach**: Default iteration utility.
### Complete Defaults Export
Details on the comprehensive export of all default values.
### Props Without Defaults
Lists props that do not have predefined default values.
### Examples and Implementation Details
Illustrates how defaults are used and their underlying implementation.
```
--------------------------------
### Import and Basic Usage of CytoscapeComponent
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/INDEX.md
Import the default export and use the CytoscapeComponent with essential props like elements, stylesheet, and layout. The `cy` prop provides access to the Cytoscape core API.
```javascript
// Default export
import CytoscapeComponent from 'react-cytoscapejs';
// Usage
{...}}
/>
```
--------------------------------
### Initialize and Render React Cytoscape.js Graph
Source: https://github.com/plotly/react-cytoscapejs/blob/master/demo.html
This snippet initializes Cytoscape.js with specific properties and renders it within a React component. It sets up event listeners for dynamic updates.
```javascript
window.addEventListener('DOMContentLoaded', function () {
const exampleProps = {
id: 'cy',
className: 'foo bar',
style: { 'border': '1px solid #ccc', 'width': '400px', 'height': '400px' },
global: 'cy',
elements: [
{ data: { id: 'a', label: 'apple' }, position: { x: 0, y: 0 } },
{ data: { id: 'b', label: 'banana' }, position: { x: 100, y: 0 } },
{ data: { id: 'c', label: 'cherry' }, position: { x: 200, y: 0 } }
],
layout: { name: 'preset' }
};
class TestComponent extends React.Component {
constructor(props) {
super(props);
props.setStateRef(this.setState.bind(this));
this.state = exampleProps;
}
render() {
return React.createElement(ReactCytoscape, this.state);
}
}
const textBox = document.getElementById('props');
const btn = document.getElementById('update');
btn.addEventListener('click', () => {
update(JSON.parse(textBox.value));
});
let update;
ReactDOM.render(
React.createElement(TestComponent, {
setStateRef: ref => update = ref
}),
document.getElementById('root')
);
textBox.value = JSON.stringify(exampleProps, null, 2);
});
```
--------------------------------
### Server-Side Rendering (Headless) for Graph Analysis
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/lifecycle-and-patterns.md
Utilize this pattern for performing graph analysis, such as counting nodes and edges or calculating centrality, without rendering the graph visually. Set `headless={true}` to enable this mode.
```javascript
class GraphAnalyzer extends React.Component {
constructor(props) {
super(props);
this.state = {
nodeCount: 0,
edgeCount: 0
};
}
analyzeGraph = (cy) => {
const nodeCount = cy.nodes().length;
const edgeCount = cy.edges().length;
this.setState({ nodeCount, edgeCount });
// Perform other analysis
const betweenness = cy.elements().betweennessCentrality();
console.log('Betweenness centrality:', betweenness);
}
render() {
const { nodeCount, edgeCount } = this.state;
return (
<>
Nodes: {nodeCount}, Edges: {edgeCount}
>
);
}
}
```
--------------------------------
### Dynamically Update Graph in React
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/README.md
Manage and update graph elements dynamically in a React component. This example shows how to add new nodes to the graph based on user interaction.
```javascript
class DynamicGraph extends React.Component {
constructor(props) {
super(props);
this.state = { elements: [] };
}
addNode = () => {
this.setState(prev => ({
elements: [...prev.elements, { data: { id: `node${prev.elements.length}` } }]
}));
}
render() {
return (
<>
>
);
}
}
```
--------------------------------
### React Component componentDidUpdate Example
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/lifecycle-and-patterns.md
This snippet demonstrates the componentDidUpdate lifecycle method. It is called after props or state changes, triggering automatic updates to the Cytoscape graph via the patch function.
```javascript
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = { nodes: 1 };
}
addNode = () => {
this.setState({ nodes: this.state.nodes + 1 });
}
componentDidUpdate(prevProps) {
// Called whenever props or state change
// Cytoscape updates automatically via patch()
}
render() {
return (
<>
>
);
}
getElements() {
const elements = [];
for (let i = 0; i < this.state.nodes; i++) {
elements.push({ data: { id: `node${i}` } });
}
return elements;
}
}
```
--------------------------------
### Dynamically Update Graph Elements
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/quick-start.md
Add new nodes to the graph dynamically by updating the component's state. This example shows how to append a new node to the existing elements array.
```javascript
class DynamicGraph extends React.Component {
constructor(props) {
super(props);
this.state = {
elements: [{ data: { id: 'n1' } }]
};
}
addNode = () => {
const newId = 'n' + (this.state.elements.length + 1);
this.setState(prevState => ({
elements: [...prevState.elements, { data: { id: newId } }]
}));
}
render() {
return (
<>
>
);
}
}
```
--------------------------------
### Configure Graph Layout
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Use the 'layout' prop to automatically position nodes. Specify the layout name, such as 'random' or 'cose-bilkent'.
```jsx
layout: {
name: 'random';
}
```
--------------------------------
### Access Cytoscape API via cy Prop
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
Use the 'cy' prop with a React ref function to get a reference to the Cytoscape 'cy' instance. This allows direct access to the Cytoscape API for advanced manipulation.
```jsx
class MyApp extends React.Component {
render() {
return { this.cy = cy }}>;
}
}
```
--------------------------------
### Common Cytoscape API Methods
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/quick-start.md
Demonstrates essential Cytoscape.js API methods for viewport control, element access, event handling, and layout management.
```javascript
// Viewport control
cy.zoom(1.5);
cy.pan({ x: 100, y: 50 });
cy.fit(); // Fit all elements in view
// Element access
cy.nodes(); // Get all nodes
cy.edges(); // Get all edges
cy.getElementById('node1'); // Get specific element
// Event handling
cy.on('tap', 'node', (event) => {
console.log('Clicked node:', event.target.id());
});
// Layout
cy.layout({ name: 'cose' }).run();
```
--------------------------------
### Render with Default Props
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/api-reference/defaults.md
Use this snippet when you want to render the Cytoscape component with all default styles, layout, and behavior. No additional props are required beyond basic styling for dimensions.
```javascript
import CytoscapeComponent from 'react-cytoscapejs';
// Uses all defaults
// Output shows example graph with default styles and layout
```
--------------------------------
### CytoscapeComponent Usage
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/INDEX.md
Demonstrates the basic usage of the CytoscapeComponent by passing essential props like elements, stylesheet, and layout. The `cy` prop provides access to the Cytoscape core API.
```APIDOC
## CytoscapeComponent
### Description
A React component for rendering interactive Cytoscape.js graphs.
### Usage
```jsx
{
console.log('Cytoscape instance:', cy);
}}
/>
```
### Props
- **elements** (array) - Required - An array of node and edge objects defining the graph structure.
- **stylesheet** (array) - Optional - An array of Cytoscape.js stylesheet rules.
- **layout** (object) - Optional - Configuration for the graph layout algorithm.
- **cy** (function) - Optional - A callback function that receives the Cytoscape instance (`cy`) when it is ready.
```
--------------------------------
### Use React Cytoscape.js with Immutable.js
Source: https://github.com/plotly/react-cytoscapejs/blob/master/_autodocs/quick-start.md
Integrate React Cytoscape.js with Immutable.js for efficient state management, especially with large graphs. Custom 'get', 'toJson', 'diff', and 'forEach' props are provided to handle Immutable data structures.
```javascript
import Immutable from 'immutable';
const get = (object, key) => {
if (Immutable.Map.isMap(object) || Immutable.List.isList(object)) {
return object.get(key);
}
return object[key];
};
const toJson = (object) => {
if (Immutable.isImmutable(object)) {
return object.toJSON();
}
return object;
};
const diff = (objectA, objectB) => objectA !== objectB;
const forEach = (list, iterator) => list.forEach(iterator);
```
--------------------------------
### Use External Layout Extension
Source: https://github.com/plotly/react-cytoscapejs/blob/master/README.md
To use external layout extensions like 'cose-bilkent', register the extension with Cytoscape.use() before rendering the component. Then, specify the layout name in the 'layout' prop.
```jsx
import Cytoscape from 'cytoscape';
import COSEBilkent from 'cytoscape-cose-bilkent';
import React from 'react';
import CytoscapeComponent from 'react-cytoscapejs';
Cytoscape.use(COSEBilkent);
class MyApp extends React.Component {
render() {
const elements = [
{ data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
{ data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
{ data: { source: 'one', target: 'two', label: 'Edge from Node1 to Node2' } }
];
const layout = { name: 'cose-bilkent' };
return ;
}
}
```