0

I have the following object coming from the BE. I load it through redux, onto a property inside my Component called user. This is the schema:

{
    user: 'root',
    perm: [
      "admin",
      "write",
      "read",
      "nodata"
    ],
    "auth": {
      "mode1": true,
      "mode2": true,
      "mode3": false
    }
}

What I want to do, is actually, map through the auth field, and for every mode, print in a span the name of each mode(THE KEY OF THE OBJECT).

So, I created a little renderSpan method to create the necessary boilerplate to map through:

  renderSpan = (authKey: string): JSX.Element => {
    const { user } = this.props;
    return (
      <div key={authKey}>
        {user && user.auth && <span> {user.auth[securityKey]}</span>}
      </div>
    );
  };

Then I mapped through it on my main render block:

  renderAuthModes = () => {
    const { user } = this.props;
    return (
      <Fragment>
        {user && user.auth && (
          <div className="container-fluid">
            {JSON.stringify(user.auth, null, 2)} // This prints the 3 modes
              <div>
                {Object.keys(user.auth).map(authKey => this.renderSpan(authKey))}
              </div>
          </div>
        )}
      </Fragment>
    );
  };

What I get in return, is 3 div with empty spans. The divs are rendered on to the DOM, but nothing is printed on the display. What am I doing wrong?

The Application is in React-Redux and Typescript.

3
  • You might have a scope issue since you're checking user in renderSpan while it is not an explicit argument. Depending on where your function is declared, user might be indeed undefined inside renderSpan. Hence giving you empty divs Commented Jul 10, 2019 at 13:00
  • But I have security checks. If user and if user.auth. How can it be undefined.. Commented Jul 10, 2019 at 13:03
  • Stupid me. Sorry for the bother guys. I was rendering the boolean values and expecting to render strings. Thanks for your time. Commented Jul 10, 2019 at 13:05

1 Answer 1

2
 {user.auth.[securityKey]}</span>}

Should be

 {user.auth[securityKey]}</span>}

Besides that everything works fine. The problem is that you are just rendering a span tag with a boolean inside, so the content will be empty... Try something like this:

<span> {user.auth[securityKey] ? 'true' :'false'}</span>
Sign up to request clarification or add additional context in comments.

1 Comment

It is the same with it as well, my mistake it, leaving it there. I console.log(user.auth[securityKey]), and I get the boolean values, of those keys. I thought I should have gotten the keys themselves. I mean, I want the values as well, but not in the span.