Explain 2 different solutions

Tell us what’s happening:
Describe your issue in detail here.
Solutin given by freecodecamp and my solution are different. Where I initialize the state, my code is written as:

this.state = {name}

Compared to the solution given as:

this.state = {
name : “Name”
}

Mine code also works. Why is this?

  **Your code so far**
class StatefulComponent extends React.Component {
constructor(props) {
  super(props);
  // Only change code below this line
    this.state = {name}
  // Only change code above this line
}
render() {
  return (
    <div>
      <h1>{this.state.name}</h1>
    </div>
  );
}
};
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36

Challenge: Create a Stateful Component

Link to the challenge:

either you can have an empty object like this {} or an object with key value pairs, the above example from fcc is a valid object declaration

There may be a bug in the 2nd test as you did not actually initialize a string value (or at least not on purpose) for the name property. I created a GitHub issue for further investigation.

UPDATE: I have documented my findings in the GitHub issue.

1 Like

Turns out the test is not reporting a false condition. However, the test will need to be changed as @tortobaka’s solution would not work if a property name like firstName would have been required. It turns out that name in JavaScript represents window.name and in this instance, there is not a name attached to window.name, so it is treated as an empty string. This is why the test passes. I have suggested the challenge be slightly changed so a property name like firstName is used.

@tortobaka Bottom line is, the purpose of the lesson was to teach you how to initialize a value for a state property. Your solution would have failed all tests if the required name would have been firstName:

class StatefulComponent extends React.Component {
constructor(props) {
  super(props);
  // Only change code below this line
    this.state = {firstName} // firstName is undefined and not a string
  // Only change code above this line
}
render() {
  return (
    <div>
      <h1>{this.state.firstName}</h1>
    </div>
  );
}
};

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.