0

I have a form with input fields that I am trying to get to change based on the validity of the user's input, but it's not working. What is it I'm overlooking? Please see the code below. The console logs are all hitting as desired... but not changes to the

export default class GeneralInput extends React.Component {
constructor(props) {
super(props)

this.state = {
  placeholderCSS: this.props.styles.placeholder || {},
  inputCSS: this.props.styles.input || {}
}
}


 onPlaceholderClick = (event) => {
event.currentTarget.parentElement.querySelector('input').focus()

}

onInputBlur = (event) => {
console.log('onblur')
let inputInfo = event.target
let inputVal = event.target.value,
    { styles } = this.props,
    fontSize = styles.placeholder.fontSize || 10,
    top = styles.placeholder.top || 4
    console.log(inputInfo.id.toString())
    console.log(inputVal.split('').length)


if(inputInfo.id == 'zip' && inputVal.split('').length < 4){
  console.log('ziphit')
  return this.setState(state =>({
      ...state.inputCSS,
      border: '3px solid red'
    }))


} else if (inputInfo.id == 'zip' && inputVal.split('').length >= 4){
      return this.setState(state => ({
          ...state.inputCSS,
          border: '1px solid green'
        }))
    }
    console.log(this.state.inputCSS)
}
  • Aside: `setStyle` is an async operation. You won't see a change to the state [using console like that](https://stackoverflow.com/a/48685595/1377002) – Andy Feb 09 '18 at 16:22

1 Answers1

1

Your CSS in state is nested one level deeper:

this.setState(prevState => ({
  inputCSS: {
    ...prevState.inputCSS
    border: '3px solid red'
  }
}));

Also note that I would recommend adding a class to your elements and conditionally changing classes instead of managing styles with state. That way, it's cleaner with separation of styles and the components.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143