Conditional rendering issue (ReactJS)

I'm having an issue rendering proper content in my component. Component has access to all the necessary store and props, I console.log to confirm that and yet it fails to render content.

I setup a store like that:

const levelDefaultState = {
level: "second"}

And my component where I want to render things depending on the current state looks like this:

import React from 'react';
import { connect } from 'react-redux'
import LevelTwo from './level2/level2'

class LevelRenderer extends React.Component {

renderLevel(){
    let currentLevel = null;
    if (this.props.level === "second") {
        currentLevel = <LevelTwo level={this.props.level} />
    } else {
        currentLevel = 'No level'
    }

    return currentLevel;
}

render() {
    console.log('store', this.props.level)


    let renderLevelConst = (this.props.level) ? this.renderLevel() : notRendered()

    function notRendered() {
        return 'Not rendered yet'
    }

    return (
        <div>
            {renderLevelConst}
        </div>
    )
}
}

const mapStateToProps = (state) => {
    return {
        level: state.level
    }
}

export default connect(mapStateToProps)(LevelRenderer);

And even though the state is "second" all the time all it renders is "no level" string. Tried to setup the initial state to "first" then changing it to "second" with setTimeout, no changes whatsoever.

What am I doing wrong?

1 answer

  • answered 2017-11-12 22:55 bee

    Try:

    if (this.props.level.level === "second") {} in renderLevel

    Since this.props.level = {level: "second", sublevel: "1.splash"} you have to call this.props.level.level to obtain the level value.