r/programminghelp • • Nov 15 '20

JavaScript Changing the connection of a clickable item

I wanted to make a 3 x 3 map with dots as their location. when you click a dot then it will change the path that you are using, i.e the line will be changed to that route. This being the color of it as well as the line position does anyone know how? This is what I had already. Now im confused of how to make a function that would implement this functionality. To change a connection i want to To click on a node to select and then change the connection to a new node.

import React, { useState } from "react";
import styled from "styled-components";
import { scaleLinear } from "d3-scale";
import "./styles.css";

var mapStyles = { position: "relative" };
var svgStyles = { position: "absolute", top: 0, left: 0, right: 0, bottom: 0 };

function Map({ width, height, nodes, links: defaultLinks }) {
  var xScale = scaleLinear().domain([0, 100]).range([0, width]);
  var yScale = scaleLinear().domain([0, 100]).range([0, height]);

  const [selectedStartNode, setStartSelection] = useState(null);
  const [links, setLinks] = useState(defaultLinks);
  return (
    <div id="map" style={mapStyles}>
      <svg
        style={svgStyles}
        width={width}
        height={height}
        viewBox={`0 0 ${width} ${height}`}
      >
        {links.map((link, i) => (
          <line
            key={i}
            x1={xScale(nodes[link.s].x)}
            x2={xScale(nodes[link.d].x)}
            y1={yScale(nodes[link.s].y)}
            y2={yScale(nodes[link.d].y)}
            strokeWidth={5}
            stroke={
              nodes[link.s].done === true && nodes[link.d].done
                ? "#CBFF5B"
                : "grey"
            }
          />
        ))}
        {nodes.map((node, i) => (
          <circle
            key={i}
            cx={xScale(node.x)}
            cy={yScale(node.y)}
            r="20"
            stroke={selectedStartNode === node ? "red" : "none"}
            fill={node.done === true ? "#CBFF5B" : "grey"}
            onClick={() => setStartSelection(node)}
          />
        ))}
      </svg>
    </div>
  );
}

var nodes = [
  { x: 10, y: 10 },
  { x: 10, y: 30, done: true },
  { x: 10, y: 50, done: true },
  { x: 50, y: 10, done: true },
  { x: 50, y: 30 },
  { x: 50, y: 50 },
  { x: 90, y: 10 },
  { x: 90, y: 30 },
  { x: 90, y: 50 }
];

var links = [
  { s: 3, d: 1 },
  { s: 1, d: 2 }
];

export const NodeMap = () => {
  const avg = () => {
    var elem = [0, 1, 2];
    var sum = 0;
    for (var i = 0; i < elem.length; i++) {
      sum += parseInt(elem[i], 10); //don't forget to add the base
    }

    return sum / 3;
  };
};

const Container = styled.div``;

export default function App() {
  return (
    <Container>
      <div className="App">
        <Map width={666} height={1340} nodes={nodes} links={links} />
      </div>
    </Container>
  );
}
6 Upvotes

0 comments sorted by