0

I am developing a table to get user input. So, I am using textFields or autocompletes to get the values, and depending on the value change the border color and the helperText. Table

Each cell has it's onChange:

onChange={(e)=>{
          setState(prevState=>({
            ...prevState,
            runTimeStamp:{
              ...prevState.runTimeStamp,
              helperText:state.runTimeStamp.evaluateHelperText(e.target.value),
              focused:true,
              error:state.runTimeStamp.evaluateHelperText(e.target.value)? true: false,
              color:state.runTimeStamp.evaluateColor(e.target.value,
                state.runTimeStamp.evaluateHelperText(e.target.value)? true: false)
            }
          }))
        }}

At this example the column is runTimeStamp. I'd like to make it become a function to have inside the onChange just the callBack, like this:

onChange={InputChange}

Is there a way to pass the column name as a string and became the setState generic?

Ex:

const InputChange =(e)=>{
          let name = e.target.name
          setState(prevState=>({
            ...prevState,
            runTimeStamp:{
              ...prevState.name,
              helperText:state.name.evaluateHelperText(e.target.value),
              focused:true,
              error:state.name.evaluateHelperText(e.target.value)? true: false,
              color:state.name.evaluateColor(e.target.value,
                state.name.evaluateHelperText(e.target.value)? true: false)
            }
          }))
        }}

The state is as follow:

  const [state,setState] =useState({

testName:{
  defaultValue:file_name,
},

runTimeStamp:{
  helperText: '',
  error: '',
  color:'',
  focused: false,
  evaluateHelperText:(text)=>{
    if (text === undefined || text === "") {
      return "Required"
    } else if (text.length < 3) {
      return "Name should contains at least 3 chars"
    }
    return false
  },
  evaluateColor:(text,error)=>{
    if(text==''){
      return "warning"
    }
    else {
      return error? 'error':'success'
    }
  },
},
Victor Santos
  • 175
  • 1
  • 8
  • To use the value of the `name` variable as the name of a property in an object literal, you use computed property notation: `setState(prevState => { ...prevState, [name]: "new value" });`. See the linked question's answers for details. – T.J. Crowder Feb 09 '22 at 12:35
  • 1
    Now it is working, thank you very much! – Victor Santos Feb 09 '22 at 12:59

0 Answers0