0

In React, I have a recursive TreeView which is working fine. When the tree is rendered, from treedata derived props like catid are passed to a TreeNode component which then renders React Link instances. These Links now can have parameters like catid:

<Link to={'/Comp1/' + catid}>{catname}</Link>

and these form the clickable items of the TreeView.

In App.js, I have a Route like this:

<Route path="/Comp1/:catid">
    <Comp1 />
</Route>

So when Link is clicked, the parameter catid is passed to the component.

This component Comp1 is structured as follows:

import React, { Component } from 'react';

export default class Comp1 extends Component {
    constructor() {
        super();
        this.state = { catid: 0 };
    }

    componentDidMount() {
        this.setState({
            catid: this.props.match.params
        });
    }

    render() {
        return (
            <div>
                Hello, I am class Comp1, clicked item { this.state.catid }
            </div>
        );
    }
};

Now, when running the App, it crashes while debug output is as follows:

debug

Mobygo
  • 51
  • 1
  • 7

1 Answers1

0

I found this somewhere.

I had to extend the Route with a render of the target component and you can then specify the params you need as props to the component, which are getting their value from props.match.params:

<Route exact path="/Comp1/:catid/:catname" render={(props) => (
     <Comp1 catid={props.match.params.catid} catname={props.match.params.catname} />
)} />

In the Link, you simply say:

<Link to={'/Comp1/' + catid + '/' + catname}>{catname}</Link>

In the target component, you can simply do:

import React, { Component } from 'react';

export default class Comp1 extends Component {


    render() {
        return (
            this.props.catname ? <div>Hello, I am class Comp1, clicked item:
            {this.props.catname} id={this.props.catid}</div> : null
        );
    }
};

Clicking another Link will update component props and rerender.

Mobygo
  • 51
  • 1
  • 7