Home > Mobile >  React Redux: Why is this nested component not receiving props from redux state?
React Redux: Why is this nested component not receiving props from redux state?

Time:12-13

I've got a parent component Course that is able to get state from redux and I'm able to log that out successfully:

import React, { Component } from "react";
import { connect } from "react-redux";
import SchoolWrapper from "../SchoolWrapper";

export class Course extends Component {
  constructor(props) {
    super(props);
    console.log("Props in course", props);
  }
  render() {
    return (
      <>
        <SchoolWrapper>Wrapped component</SchoolWrapper>
      </>
    );
  }
}

const mapStateToProps = (state) => ({
  user: state.user,
});

export default connect(mapStateToProps)(Course);

Nested in the Course component is another component SchoolWrapper that is able to get props from redux state:

import React, { Component } from "react";
import { connect } from "react-redux";
import { Nav } from "./Student/Nav";

export class SchoolWrapper extends Component {
  constructor(props) {
    super(props);
    console.log("SchoolWrapper props", props);
  }

  render() {
    return (
      <>
        <Nav />
      </>
    );
  }
}

const mapStateToProps = (state) => ({
  user: state.user,
});

export default connect(mapStateToProps)(SchoolWrapper);

However, the Nav component or any other component nested at this level is not able to access state from redux.

import React, { Component } from "react";


import { connect } from "react-redux";

export class Nav extends Component {
  constructor(props) {
    super(props);
    console.log("Nav props: ", props);
  }

  render() {
    return (
      <div>
        nav goes here...
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  user: state.user,
});

export default connect(mapStateToProps)(Nav);

Where am I going wrong?

CodePudding user response:

I think you're importing Nav wrong, here you're using a "default" export:

export default connect(mapStateToProps)(Nav);

But you try to use a "named" import:

import { Nav } from "./Student/Nav";

Nav should be imported as a "default":

import Nav from "./Student/Nav"
  • Related