상세 컨텐츠

본문 제목

redux-form

React

by nata_developer 2020. 8. 20. 15:06

본문

*https://medium.com/dailyjs/why-build-your-forms-with-redux-form-bcacbedc9e8를 참고하였습니다.

1.redux-form 이란?

  • The fields that are in the form;

  • The values of each field;

  • The focused field;

  • If the field values are valid;

  • The fields that the user have interacted with;

  • If the form is being submitted;

  • If is happening any asynchronous validation.

2. setup.

import { reducer as formReducer } from 'redux-form'

//...

const reducers = combineReducers({
  //...
  form: formReducer
})

 

import React from 'react'
import { Field, reduxForm } from 'redux-form'
import InputText from 'app/simpleForm/components/inputText'

const validateNotEmpty = value => !value ? 'Must enter a value' : null

const onSubmit = values => alert(JSON.stringify(values))

const SimpleForm = ({ handleSubmit }) => {
  return (
    <form onSubmit={ handleSubmit(onSubmit) }>
      <Field label="Country" name="country" component={InputText} validate={validateNotEmpty} type="text" />
      <button type="submit">Submit</button>
    </form>
  )
}

export default reduxForm({
  form: 'simpleForm',
  initialValues: {
    country: 'Brazil'
  }
})(SimpleForm)

high-order 컴포넌트인 reduxForm을 가지고 form 컴포넌트를 Redux와 연결한다. 

 

이것은 submisson 행동을 관장하는 handleSubmit function을 우리에게 준다. 

import React from 'react'

const InputText = ({ input, label, meta: { touched, error }}) => (<div>
  <label htmlFor={input.name}>{label}</label>
  <input {...input} type="text" />
  { touched && error && <span className="error">{error}</span>}
</div>)

export default InputText

 

field 컴포넌트는 props로서 input 컴포넌트을 취한다.

 

그리고 application 상태를 input 컴포넌트에 전달한다.

 

그리고 스토어의 상태를 업데이트 하기위해 이벤트 핸들러와 결합한다. 

 

 

 

 

'React' 카테고리의 다른 글

React Router를 이용하여 component간에 props 넘겨주기  (0) 2020.08.20
Blog App5 StreamEdit  (0) 2020.08.20
Blog App 4 StreamCreate  (0) 2020.08.20
Blog App 2 GoogleAuth  (0) 2020.08.20
react-router-dom  (0) 2020.08.20

관련글 더보기