1

Go over an object, and return a component to each attribute in the object

Hi everyone I'm new to react, I built component - I have a state of user preferences - and I do go over all preferences, and return the rating he gave to each preference - with the help of mui - I have been trying for several hours to do this, I can not.

This is the code I wrote, it runs but I do not get the component back, I do not understand why.

import React, { Component, Fragment } from 'react';
// MUI stuff
import Rating from '@material-ui/lab/Rating';
// Icons
import ListIcon from '@material-ui/icons/List';


class Profile extends Component {

  constructor(props) {
    super(props);
    this.state = 
    {preferences: {
      html: "5",
      react: "4",
      css: "4",
      angular: "3",
}};
  }

  render() {
    let profilePreferences = {preferences && (
                <Fragment>
                  <ListIcon color="primary" />
                  <hr />
                  {
                    Object.keys(preferences).map(prefer => {<Rating name={prefer} defaultValue={parseInt(preferences[prefer], base)} precision={1} readOnly/>}) 
                  }
                  
                  <hr />
                </Fragment>
              )}
    return profilePreferences ;
  }
}

export default Profile;

I think the problem is very small, but I can not find it, I just want to go over my object and for each feature, return a "rating" component of "materialUi".

Submitted December 30th 2020 by Admin

Answers
0

Currently, preferences is undefined. You need to get it from this.state.

render() { const { preferences } = this.state; // <------ Add this line let profilePreferences = {preferences && ( <Fragment> <ListIcon color="primary" /> <hr /> { Object.keys(preferences).map(prefer => (<Rating name={prefer} defaultValue={parseInt(preferences[prefer], base)} precision={1} readOnly/>)) } <hr /> </Fragment> )} return profilePreferences ; }

Admin | 9 months ago


0

The first problem of your code was that you didn't use this.state.preferences. The second problem was you are confused about the usage of {} and () parentheses in JS. The third point - Do not forget to print key when you output a list of elements.

I have edited your code. Here is a working example on codepen.

Admin | 9 months ago



Relevant Questions