user13456401
user13456401

Reputation: 479

How to convert a React JS functional component to a class component?

Hi I have this reactjs snippet I need to convert this to a class component (now it is a functional` component)

But this has to be carried out carefully since I try to get values from Form component to the Main component and prints that value within the Main component.

This is my Main.jsx

function Main(props) {
   
   const [firstName, setFirstName] = React.useState('');

   return (
     <div>
       <Form setFirstName={setFirstName} firstName={firstName} />
       <p> {firstName} <p/> // this works fine
     </div>
   );
}

And this is the Form.jsx I need this to write as a class component instead of a functional component which is it now.

function Form({ firstName, setFirstName }) {

   const handleChange = (event) => {
      setFirstName(event.target.value)
   }
   
   return (
     <div>
       <TextField onChange={handleChange} value={firstName} />
     </div>
   );
}

I tried to convert this like this, but then it doesn't print the value of firstName inside

export default class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName: "",
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = (event) => {
    this.props.firstName = event.target.value;
  };

  render() {
    return (
      <div>
        <TextField onChange={this.handleChange} value={this.state.firstName} />
      </div>
    );
  }
}
<p> {firstName} <p/> // and now this wouldn'tt work after converting this to a class component

Can someone please help me?

Upvotes: 0

Views: 55

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14365

First of all, I don't understand why you'd want to convert this to a class at all, but I'll assume that you have a good reason.

Do not re-assign props like this: this.props.firstName = event.target.value;. Data flow in React goes one direction. Top -> down. If you need to update a prop, you pass a separate prop that is a function to update the first's value (see docs on lifting state up).

If you are wanting to move the state to the Form component, just update state like this:

handleChange = (event) => {
  this.setState({ firstName: event.target.value });
};

But notice this will not update props, so this is probably not what you're looking for.

To be more similar to your functional component setup, don't use state at all in Form and keep it in Main like it was before. This means we can cut out the constructor as well.

export default class Form extends Component {
  handleChange = (event) => {
    this.props.setFirstName(event.target.value);
  };

  render() {
    return (
      <div>
        <TextField onChange={this.handleChange} value={this.props.firstName} />
      </div>
    );
  }
}

Upvotes: 1

Related Questions