React Create a Controlled Input explanation please

This is my first post on forum so bare with me.
Also I would like to state that PLEASE include Vue and Swetle, i realy dislike React and I am doing it just to get you precius certificate.

And would also thank you for making this great website .

Tell us what’s happening:

  **Your code so far**

class ControlledInput extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: ''
  };
  // Change code below this line
this.handleChange = this.handleChange.bind(this)
  // Change code above this line
}
// Change code below this line
handleChange(event){
this.setState(state =>{
console.log(event.target.value)
return this.state.input = event.target.value
})
}
// Change code above this line
render() {
  return (
    <div>
      { /* Change code below this line */}
      <input onChange={this.handleChange}></input>
      { /* Change code above this line */}
      <h4>Controlled Input:</h4>
      <p>{this.state.input}</p>
    </div>
  );
}
};

Please help me understand why my code is wrong at handleChange(event){ part. That was my first attempt.
In upper code i get can't access property "value", event.target is null. I tried passing it as argument but none of my tries worked.

After getting a hint i wrote it like this:

class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ''
    };
    // Change code below this line
this.handleChange = this.handleChange.bind(this)
    // Change code above this line
  }
  // Change code below this line
handleChange(event){
  this.setState( {
  input : event.target.value
})
}


  // Change code above this line
  render() {
    return (
      <div>
        { /* Change code below this line */}
        <input onChange={this.handleChange}></input>
        { /* Change code above this line */}
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
};

There is no errors in console. I get p element updated, i believe the state too by this logic. But i still get

Typing in the input element should update the state and the value of the input, and the p element should render this state as you type.
Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0.

Challenge: Create a Controlled Input

Link to the challenge:

Oh I forgot too set the value in 2nd code. But If someone would explain the first attempt error I would be grateful.

Welcome there,

Just to clarify: You do not need to complete any of the lessons, in order to claim the certifications - only the 5 projects at the end are required. Also, whilst discouraged, you are welcome to use VUE or any other frontend library to complete the projects. Just take note that the tests will not have defined behaviour for any library outside of those in the curriculum.


Think about this line from a pure JavaScript perspective. It is equivalent to this:

function myFunc() {
  return a = 1;
}

What does myFunc return? Also, what does setState expect the callback function to return?

Now, from a React standpoint:

  • NEVER directly mutate state in React . This causes unexpected results, at best.

Hope this clarifies and helps

1 Like

Just a quick FYI regarding the first code example you posted. You do not have access to event.target.value inside the setState updater function in React 16.4, which is what the curriculum is using. It would work in React 17 (I’m just talking about access to event.target.value, not the incorrect state usage you have).

Example Codesandboxes

React 16 event.target inside setState updater function (will crash) - CodeSandbox

https://codesandbox.io/s/react-17-eventtarget-inside-setstate-updater-function-1fb71?file=/src/App.js

As for the second example. You have to “connect” the value attribute to the state to make a controled component.

2 Likes

Thanks for the anwser.
Yes i am aware that I can use others, but I am in process of learning any and I don’t like shortcuts. That being said I was more refereeing to maybe made Courses for other library’s as choices, I really like freecodecamp concept, learning paths and courses, just saying that I had a choice I would chose another JS library.

But on the end of the day i know i will come out of this struggle smarter :smiley: And will finish as it was intended with React.

And yes your anwser helped.
Cheers

1 Like

Oh thanks a lot, so it wasn’t poorly my fault, and wrong logic (commenting event mistake), good to know. :smiley:
I appreciate the anwser.

About React. I think you may find the functional style using hooks more enjoyable than the class-based component style (less verbose and more declarative). fCC does not teach that yet.

It won’t be like Vue or Svelte where you have a templating system (or directives) with build-in functionality (like looping or conditions). JSX may look like HTML but isn’t and you have to pretty much do all the logic and functionality by hand using JS. E.g. using map vs {#each expression as name} type template looping.

As for teaching other frameworks. It’s a lot of work to create challenges, tests and be able to give good support to them. It wouldn’t be very good if we taught Svelte but nobody on the forum was able to help with it (some would, but not a lot).

I would suggest you look at other React learning resources as well. You can check out YouTube, etc. The fCC YouTube channel has React tutorials, as well as Vue and Svelte.

1 Like

Oh my I just googled this and it does look way more user friendly. I will definitely keep this this in mind. I have bookmarked a lot of recurses already I just thought forcing myself passing FFC courses first might be good first step in learning it.

I see those are from 16.8 version so, not yet here on FFC?

But as they are passing they get intimidating, seems a lot of hustle. And a lot of articles tend to point that as a down side of React.

But I am looking forward to learn the differences in this frameworks in long run.

The functional style is a different paradigm. It would take a lot of work to update the current React curriculum. We would have to have lessons on the different hooks (state in function components) and there would be very little of the current code that we would be able to reuse (as well as the tests). Some of the base JSX might be fairly reusable but not much more than that.

I don’t know if a major update to the React curriculum will happen in the foreseeable future. By then it will likely be project-based and not just individual challenges like it is now. But there are tons of great free React learning material out there.


As for React being more “ceremonial” than some other frameworks, I would say that is an accurate statement. Just wait until you get to the Redux part of the curriculum, you ain’t seen nothing yet.

But that is also what attracts some people. It’s a bit of a running joke that React got so popular because coders with their CS background wanted high-paying jobs as experts and engineers. So they picked the framework you can over-engineer the best. It’s facetious (but with a little truth to it).

Don’t get me wrong, I personally do like React. You can write some pretty nifty and clean code, especially with hooks and composition.

As to hooks and functional components vs class components … I do hope that we eventually expand the React curriculum to include more modern patterns, but I would hope that we keep the class based stuff. Personally I tend to favor the functional/hook style but there is still a lot of code out there based on classes and we have to deal with it, so you kind of have to know it and will for some time. And if you understand class based components, switching to functional and hooks is fairly simple.

I agree to know both is valuable as a React developer. But for beginners, it can muddy the waters. For example, if functional got slotted in and ended up like the ES6 part of the JS curriculum (i.e. lack of good integration) it might do more harm than good.

Most tutorials now mention class components as a preamble side note and I don’t think if the curriculum was written today we would have much reason to fully teach the class-based component style.

I’m sure the React team has/had some of the same issues with their own docs.

Not sure that is true for beginners.

I also remember when hooks just came out not everyone was on board and there was a lot of confusion. So I wouldn’t say the switch was that simple.

But man does going back to class components feel like a slugfest now, so much more verbose and this, this, this, this, everywhere. I would never write a class component willingly today (unless I got paid and had to that is).

Right, but that’s what I meant by “understand”. To me that’s assuming a level of comfort with how React works and you are probably familiar with functional components and functional patterns. Yeah, hooks are a little confusing at first, and don’t always map 1:1 well to lifecycle methods, but I think it’s not too bad of a leap if you’re already at an intermediate level and already have a solid grasp of pre-hook React.

I still aver that a dev needs to know class based components. At my current job, I mostly write functional/hooks, but there is existing code that I have to maintain and sometimes I have to integrate in with patterns that needs classes so I have to write a few. If I didn’t know class components, I would be lost. I would expect the dependence on class components to diminish with time, but I think it will be with us for a while.

But yeah, in my personal projects, I haven’t written a class component in quite some time. In find the functional pattern cleaner.

I think part of the problem is that React is also the “old-fashioned” way - everything is a class, every thing has a constructor, you have to bind this for everything (instead of arrow functions), setting initial state in the constructor, etc. It makes the class component bigger and clunkier than it needs to be.

But this is all probably a discussion for another time.

As for React being more “ceremonial” than some other frameworks, I would say that is an accurate statement. Just wait until you get to the Redux part of the curriculum, you ain’t seen nothing yet.

Well thanks for heads up. :slight_smile:

Also i might add im happy you two are discussing this. I have learned something from it , but then also im rethinking my plan of first going thru all React courses here. They are a bit scary (I am not here bashing there value of course), and maybe I should switch to projects and start learning Vue or Swetle to build them in it and get FFC certification, basically invest more time in them, and make React side gig.

I feel very comfortable with vanilla JS to make all projects, and was thinking well how hard React can be. But well as it turns out, not that easy…

I will and could come back from time to time and finish React here just to get knowledge of it. Well at least of React classes :smiley:

Edit:
I will also say that i value FFC certification a lot, just from stand point of me going thru courses and knowledge gain from that. That being said and looking at title of this curriculum for Font end libraries still have a feeling, option should be included, at least Angular or Vue (to learn not finish in). So I have feeling that me finishing it in something other then React and not going thru all the courses will feel like bit a chitin.

So i am looking forward to any updates in future on this subject. And even on possibility to to learn React hooks.

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