0

I am currently trying to redirect the user when an article of my website get clicked, however, I am getting the following error:

TypeError: Cannot read property 'props' of undefined onArticleClicked

13 |

14 | onArticleClicked() {

15 | // go to http://my-react-app.com/article/{articleID}

16 | this.props.history.push("/article/" + this.article.ID)

17 | }

18 |

19 | priceToDouble() {

There is my component:

import React from 'react'
import { Image } from 'react-bootstrap'
import { centimesToDouble } from '../../utils/price_converter';

export default class Article extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            article: props.article
        }
    }

    onArticleClicked() {
        // go to http://my-react-app.com/article/{articleID}
        this.props.history.push("/article/" + this.article.ID)
    }

    priceToDouble() {
        return centimesToDouble(this.state.article.price / 100) + "€"
    }

    render () {
        return (
            <div onClick={this.onArticleClicked}>
                <Image src={this.state.article.variants[0].pictureUrl} responsive />
                <h3>{this.state.article.name}</h3>
                <p>{this.priceToDouble()}</p>
            </div>
        )
    }
}

I don't get it because, based on other stackoverflow answers, I should be able to redirect like that, why can't I?

I am trying to learn reactjs through this project, feel free to give any advices, thank you

Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
Emixam23
  • 3,854
  • 8
  • 50
  • 107
  • 1
    put this line in the constructor: `this.onArticleClicked = this. onArticleClicked .bind(this);` – Mayank Shukla Feb 05 '18 at 09:26
  • 1
    Also check [Programmatically navigate using React router](https://stackoverflow.com/questions/44127739/programmatically-navigate-using-react-router/44128108#44128108) apart from the duplicate – Shubham Khatri Feb 05 '18 at 09:28
  • Ok, I then took a look at both of your comments, thank you ! It seems to work, however **console.log(this.article)** is displaying *undefined* in `onArticleClicked()` – Emixam23 Feb 05 '18 at 09:37
  • 1
    @Emixam23, this.article is anyways undefined, you have to use `this.state.article` – Shubham Khatri Feb 05 '18 at 09:44
  • 1
    @ShubhamKhatri So use to develop in C#.... my bad thank you ! – Emixam23 Feb 05 '18 at 09:46

0 Answers0