tallman
tallman

Reputation: 129

In React, how to add a URL "string" as an object's property, from a Link or other component

In React, I'm setting an object's URL property (specifically, amcharts chart bullet.url), which is a string, to "../members/{member.name}" It renders with no issues. Clicking the link navigates to the page correctly. However, it seems all the previously loaded states need to be reloaded. Is it a new React "session?"

I've tried setting the property using various expressions using Link. But none seem to compile as expected. Most articles I've found relate to basic usage of Link or persisting state.

The following works rendering and navigating, but all state is gone on new page:

let series = chart.series.push(new am4charts.LineSeries());
let bullet = series.bullets.push(new am4charts.CircleBullet());
bullet.url = "../Members/{member.name}";

I'm thinking there's a React concept I'm missing or an easy way to set a link's URL. I'd like to navigate without "resetting" all the previously loaded states.

Upvotes: 5

Views: 16792

Answers (3)

notacouch
notacouch

Reputation: 3655

Instead of using urls, use a click ("hit") event to stay within the React ecosystem. If you allow the chart component to be rendered via React Router and export it with withRouter, you can take advantage of this.props.history on the component itself. As for how to handle the member's name, presuming the bullet is actually the template for other bullets, I personally believe the member's name should be part of the chart's data. E.g.

Main component:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Route, BrowserRouter as Router } from "react-router-dom";

// ...

// main component's render
  <Router>
    <React.Fragment>
      <Route
        path="/"
        render={props => <App {...props} />}
      />
      <Route
        path="/Member/:name"
        render={props => <Person {...props} extra="via router" />}
      />
    </React.Fragment>
  </Router>

Component that has your chart (e.g. App):

import React from "react";
import { withRouter } from "react-router-dom";
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";

// App's componentDidMount() ...

// ...chart code...

// Member names found in bullet data
chart.data = [ { name: "...", /* ... */ }, /* ... */ ];

// Since we're not using `url`, manually change the cursor to a pointer on hover
bullet.cursorOverStyle = am4core.MouseCursorStyle.pointer;

// Bullet click event
bullet.events.on("hit", event => {
    this.props.history.push('../Members/' + event.target.dataItem.dataContext.name);
});

// ... end App

export default withRouter(App);

Here's a fork of our Column charts with images at top demo in React that when clicking the bullet/images, both updates the main component's state as well as goes to a new URL, and both load the person's info:

https://codesandbox.io/s/olpzok2rxz

If the member.name is not part of the chart data and cannot be, it would help to have a sample of your app whether on JSFiddle or CodeSandbox so we can help further.

Upvotes: 1

ABC
ABC

Reputation: 2148

In response to my comment.

The state of a component is always a Javascript object, and is stored in the main memory. Each components state is mutating until the page refreshes or closes. After that, the page will be initialized with its initial state.

You could use localStorage or cookies for functionality or a mixin.

Example

const Example = React.createClass({
    getInitialState: function () {
        return JSON.parse(localStorage.getItem('counter') || '{}');
    },
    componentDidMount: function () {
        let self = this;
        setInterval(function () {
            this.setState({
                ticks: this.state.ticks + 1 // Increment
            });
            localStorage.setItem('counter', JSON.stringify(this.state)); // Store
        }, 1000); // Interval
    },
    render: function () {
        return (
            <span>{this.state.ticks}</span>
    );
    }
});

Link Variable

// "../Members/{member.name}";
// Make sure member.name is not an object, but a string
<a href={ `#/..Members/${members.name}` }>{members.name}</a>

Why do you have an error?

Type.js:171 Uncaught Error: Expected a string or number but got [object Function]

This is because you are accessing an object value that is a function. You need a string. If it is not a string convert it Object.toString();.

// You are not accessing the object correctly
const param = {
  id: function() {
     // This is what it's seeing
  },
  // Needs to be
  id: '../members/id'
}

console.log(param.id);

Upvotes: 0

Kishan Jaiswal
Kishan Jaiswal

Reputation: 664

bullet.url = `'../Members/${member.name}'`;

add this way in object from to url

Upvotes: 0

Related Questions