Search code examples
reactjsreact-apolloapollo-clientapollo-boost

this.props not accessible when using ApolloClient


I am using apollo-boost and I have created an ApolloClient and I want to do some redirection after a mutation is run but I cannot access the props

index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { ApolloProvider } from "react-apollo";
import ApolloClient from "apollo-boost";

import "./bootstrap";
import Routes from "./RoutesComponent";

const client = new ApolloClient({
  uri: "http://localhost:4000/graphql"
});

const Root = () => {
  return (
    <ApolloProvider client={client}>
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    </ApolloProvider>
  );
};

ReactDOM.render(<Root />, document.querySelector("#root"));

RoutesComponent

import React, { Component } from "react";
import { Route, Switch } from "react-router-dom";

import Register from "./authenticate/register/RegisterComponent";
import Login from "./authenticate/login/LoginComponent";
import Product from "./customers/product/ProductComponent";
import AddProduct from "./customers/add-product/AddProductComponent";
import Products from "./customers/products/ProductsComponent";
import AdminProduct from "./admin/product/ProductComponent";
import AdminProducts from "./admin/products/ProductsComponent";

class RoutesComponent extends Component {
  render() {
    return (
      <Switch>
        <Route path="/products/new" render={() => <AddProduct />} />
      </Switch>
    );
  }
}
export default RoutesComponent;

AddProductComponent

import React, { Component } from "react";

class AddProductComponent extends Component {
  render() {
    console.log(this.props);
    return (
      <div>
        <h1>AddProductComponent</h1>
      </div>
    );
  }
}
export default AddProductComponent;

this.props in console shows {}

to mitigate this I also tried using history package and it changes the url but redirection does not work

I can do the redirection using state but I would rather do it using history prop than state.

any advise on this will be appreciated.


Solution

  • The Route's render function takes props as argument and since you're not passing it, it won't be available in the component

    <Route path="/products/new" render={() => <AddProduct />} />
    

    Fixed:

    <Route path="/products/new" component={AddProduct} />