2

Im trying to learn react but I cannot get my program to compile. When I run my code, it says it fails to compile and says that state is not defined. I followed what was on the react website for setting the state, but it still says it is not defined. Ive searched all over online and it says this is how state should be set up. Please help!

const App = () => {
    state = {name: "Jim"};

    return (
        <Profile name={this.state.name} />
    );
}
1
  • 1
    If you're trying to learn react, then stop whatever it is you're doing, and start at reactjs.org/tutorial/tutorial.html because it's a) really well written and b) covers everything you need to know to get started. Commented Feb 26, 2019 at 23:29

2 Answers 2

1

You're trying to initialize the state in a Stateless component. You should change it to be a Stateful component. You're also trying to set the state without settings the state with something like componentDidMount() or a constructor() function. You can turn it into a Stateful component and call the constructor function like this:

class App extends React.Component {
    constructor() {
        super();
        this.state = { name: "Jim" };
    }
    render() {
        return (
            <Profile name={this.state.name} />
        );
    }
}

You can read about Stateless and Stateful components here.

Sign up to request clarification or add additional context in comments.

2 Comments

That's not how you assign state in a constructor
You're right. I was in a bit of a hurry when I posted this. Note that it would still work if you later set the state, which I also mentioned in the post.
0

You're trying to use state like a class property, but you're inside a function body, not a class. You want const state = {name: "Jim"}; or to make your component a class.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.