Home > Blockchain >  How to refactor class component to functional(have to rerender, got undefined )
How to refactor class component to functional(have to rerender, got undefined )

Time:10-03

In IssueEdit component the main state of my app is stored(which I got from an API call). I pass that data to a specialized input component where issue.effort have to be converted to string and stored as string. It works well in case of Class Component. I tried to refactor the class component to functional component and this is when the problem started. The problem is that after first render formattedValue is undefined so nothing is displayed. The input field is empty. How to make functional component behave equally as class component?

export const IssueEdit = () => {

const [issue, setIssue] = useState({effort: 5})
       ...
return (
  ...
        <td>
                                <NumInput
                                    name="effort"
                                    value={issue.effort}                
                                />
       </td>
  ...

                         *** Class Component ***
function format(num) {
     return num != null ? num.toString() : '';
}

export default class NumInput extends React.Component {
  constructor(props) {
     super(props);
      this.state = { value: format(props.value) };
      this.onChange = this.onChange.bind(this);
   }
   onChange(e) {
      if (e.target.value.match(/^\d*$/)) {
         this.setState({ value: e.target.value });
   }
}

render() {
  const { value } = this.state;
   return (
     <input
       type="text"
       value={value}
       onChange={this.onChange}
     />
   );
  }
}

                      *** Functional Component ***

export const NumInput = ({ value }) => {
const format = (num) => {
    num != null ? num.toString() : ''
}

const [formattedValue, setFormattedValue] = useState(format(value))

const onChange = (e) => {
     if (target.value.match(/^\d*$/)) setFormattedValue(target.value)
}

return (
    <input
        type="text"
        value={formattedValue}
        onChange={onChange}
    />
 )

}

CodePudding user response:

Is this just a typo ? onChange={onChangeValue} should be onChange={onChange}.

You named your function onChange in the functional component but are then invoking it with onChangeValue which doesnt exist.

Another problem as the author commented I'll edit so everyone can see:

const format = (num) => {
    num != null ? num.toString() : ''
}
// what u meant
const format = (num) => {
    return num != null ? num.toString() : ''
}
  • Related