Enhance React-D3-Graph ViewBox

I have a dataset named actors storing nodes and links called scratch. The structure is as follows...

{
  "nodes": [
    {
      "id": "Guardians of the Galaxy"
    },
    {
      "id": "Chris Pratt"
    },
    {
      "id": "Vin Diesel"
    }
  ],
  "links": [
    {
      "source": "Guardians of the Galaxy",
      "target": "Chris Pratt"
    },
    {
      "source": "Guardians of the Galaxy",
      "target": "Vin Diesel"
    }
  ]
}

I'm working on displaying this graph in my React app, but facing an issue with the small viewbox size, which limits larger datasets from fitting on screen. Is there a way to set specific height and width values for the viewbox? I found that using viewbox={0 0 9000 9000} works for larger datasets. Below is my code snippet...

import React, { useRef, Component }  from "react";
import Navbar from "./components/Navbar"
import './App.css';
import { Graph } from "react-d3-graph";
import { BrowserRouter as Router } from 'react-router-dom'
import myData from './Data/scratch.json'

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: myData,
            width: 9000,
            height: 9000,
            svgRef: useRef
        };
    }

    render() {
        const myConfig = {
            nodeHighlightBehavior: true,
            node: {
                color: "green",
                size: 120,
                highlightStrokeColor: "blue"
            },
            link: {
            }
        };

        let svgRef = this.state.svgRef;


//Function to toggle node colors on click
        const OnClickNode = function (nodeName) {
            let modData = {...svgRef.state.data};
            let selectNode = modData.nodes.filter(item => {
                return item.id === nodeName;
            });
            selectNode.forEach(item => {
                if (item.color && item.color === "red") item.color = "green";
                else item.color = "red";
            });
            svgRef.setState({data: modData});
        };



        //.attr("viewBox", "0 0 300 300")
        //.attr("viewBox", "0 0 9000 9000")
        return (
            <Router>
                    <Navbar />
                    <Graph
                        id="graph-name" // id is mandatory, if no id is defined rd3g will throw an error
                        data={this.state.data}
                        viewBox={"0 0 500 500"}
                        height={this.state.height}
                        config={myConfig}
                        onClickNode={OnClickNode}
                 >
                    </Graph>
            </Router>
        );
    }
}
export default App;

I've seen examples using div, but since I have another component called Navbar positioned above the graph, it doesn't work well together within a div.

Answer №1

After some troubleshooting, I finally pinpointed the issue. It turns out that my App.css file was missing a crucial piece of code:

svg{
    background: #eee;
}

To resolve the problem, I added the following code snippet:

svg {
  min-width: 1863px;
  min-height: 800px;
  max-height: 9000px;
  max-width: 9000px;
  background: #eee;
}

However, upon implementing this fix, I noticed that the image is now extremely zoomed in, which is something I'll need to address next.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining POST information from Web2py to a personal HTML document

Dealing with heavy jQuery cross-domain issues, I have turned to using web2py as a workaround. I am sending POST data from a local HTML file to my web2py server, which then makes a Python POST request to a second server (solving the cross-domain problem) a ...

The issue is that the JavaScript output is not being displayed after submitting the HTML

I'm looking to add not only a submit button for the default form action, but also an extra button for a second action. Here is the code I have so far: <html> <head><title></title> <?PHP $Input = ""; if(isset($_POST['I ...

Visual Editor for React Material UI - A Unique Designing Experience

I've launched a new open-source project focused on creating a visual editor specifically for React Material UI. If you're interested, feel free to check out the project link. The idea behind this project is to allow users to easily drag and drop ...

Long taps do not activate the context menu in the mobile interface, as noted in the Google Maps API

During the development of my project, I encountered an issue with the Google Maps API not functioning correctly on mobile devices. I am utilizing GMaps.js, but even that example does not properly support right-click (long tap event). Here is a snippet of ...

Which specific web framework supports the functionalities of Microsoft Dynamics CRM 2011?

Is there an SDK available from Microsoft that can help me create a web product with similar rich ajax features as Microsoft Dynamics CRM 2011? I have considered using Microsoft SharePoint Foundation 2010, but I am concerned that it is designed for small o ...

The CSS isn't functioning correctly in the HTML file as it is in the CSS file

When I added this code directly to my html file, it worked perfectly: <style type="text/css" media="screen"> #headerimg { display: block; background-image: url('/Content/images/epp/ebweblogo1.gif'); background- ...

What steps should I take to integrate my Node.js code into a website successfully?

I have a node.js code that works perfectly in the terminal. How can I display the console.log output on localhost and later on Heroku? Since I am still a beginner, I find express challenging. Do you think I should use it? I also tried Browserify. const p ...

Arrange moving shapes in the same spot

Every time I press the button, a unique shape is generated. These shapes are dynamic and can range from polygons to circles (there are hundreds of shapes). Each shape is composed of a series of lines. The problem arises when each shape is positioned diff ...

Tips on incorporating a personalized components directory into your Gatsby project

I am looking to integrate some custom React components from a GitHub repository into my Gatsby project. However, I am unsure about how to include an external folder. The structure of the components folder that I want to incorporate is as follows: |-- /dis ...

AngularJS controller experiencing scope() function returning undefined issue

I've been working with a function inside the controller: $scope.passValues = function (param1){ return "foo"; }; console.log($scope.passValues()); It logs foo, but then I tried this: $scope.passValues = function (param1){ return param1; ...

Toggle between tabs by dynamically selecting radio buttons

On my webpage, I have numerous tabs following the same structure as seen on the angular-ui page. Each section contains tabs for both Markup and Javascript. My goal is to implement two radio buttons at the top of the page that can switch all tabs to either ...

What is the process of declaring a react-icons icon in TypeScript?

Having a dilemma with declaring the icon in my array that contains name and icon. export const SidebarMenuList: SidebarMenu[] = [ { name: "Discover", icon: <AiOutlineHome />, id: SidebarCategory.Discover, }, ] The SidebarMe ...

JQuery - Select element by clicking outside

I'm trying to figure out how to hide an element when clicking outside of it. Found a solution at: https://css-tricks.com/dangers-stopping-event-propagation/ $(document).on('click', function(event) { if (!$(event.target).closest('#m ...

The JQuery get method fails to send a request to the server

When running the following jQuery code to load a partial page onto a hidden div, everything works fine on my local machine. However, once I add the code to the server, the partial page does not load. Any suggestions on why this might be happening? var u ...

Even though my form allows submission of invalid data, my validation process remains effective and accurate

Here is the code I have written: <!doctype html> <html lang="en"> <head> <title>Testing form input</title> <style type="text/css></style> <script type="text/javascript" src="validation.js"></script> &l ...

Retrieving a Promise's value for an HTML Element

Hello, I'm new to working with React and JavaScript and could use some assistance. I have a function that returns a Promise that includes an interface. My goal is to access a variable in the interface and use it within <dl><dt>{//string va ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

The mandatory field in the TextField component of Material UI fails to work upon submission

I have integrated the textfield component from the Material UI library into my React application for user input. However, I am facing an issue with the 'required' attribute not working as expected when submitting the form. The input data is being ...

What steps can be taken to enable CORS on an existing server that was created with createServer function?

The following code snippet is what I currently have: var gqlServer =require('./server.js') var server=gqlServer() var port = process.env.PORT||5000 server.listen({port:port}, ()=> console.log(` ...

Exploring Vue and Webpack's tree shaking functionality, side effects management, and its impact on CSS: Loading unused component CSS

We are currently grappling with the challenge of effectively implementing tree shaking for CSS within Vue Single File Components using Webpack. Within our package.json file, we have specified: "sideEffects": ["*.css", "*.less","*.vue"], which appears to b ...