티스토리 뷰

I was working on checkboxes in one of my React Components.


I kept on getting the following error.




Looking into it in depth, I ran into this SO post that points at the heart of the issue.


https://stackoverflow.com/questions/36715901/reactjs-error-warning



So React deals with form control in two ways


1. Controlled Components

  • `value` for most `<input>` and `checked` for `checkbox` or `radio`
  • `onChange` handler
 
React controls the condition of this component by updating props or state. For React to update the element's condition upon re-render, `onChange` handler is needed so we can update the component's state or notify the parent component (props).

const { render } = ReactDOM;

class Demo extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      checked: true
    };
    
    this.checkboxHandler = this.checkboxHandler.bind(this);
  }
  
  checkboxHandler(e) {
    this.setState({
      checked: e.target.checked
    });
  }
  
  render() {
    return (
      <  input type="checkbox" checked={this.state.checked} onChange={this.checkboxHandler}  />
    );
  }
}

render(
  < Demo />,
  document.getElementById('demo')
);



2. Uncontrolled Components
  • `defaultValue` or `defaultChecked`
 
You are telling React to set the default value and after that the element's state is up to the user to update the value, usually using refs.

<  input 
type="checkbox" 
defaultChecked={this.props.checked=}  />


'Comp Sci > Engineering' 카테고리의 다른 글

[ReactJS] Controlled and Uncontrolled Components  (0) 2018.07.27
댓글
댓글쓰기 폼