0

I am trying to write a SPA with React.

I get a JSON-Object from a webservice which validates the Inputfields.

Now I want so set the Style of the Inputfield depending on the answer of the Webservice. At example the Style should be:

style={{borderColor: 'green',   boxShadow: '0 0 5px green',}}

when the JSONValue is 0

<Input
    style = ???
    ...
/>

My JSON looks like this:

{
    "validate": {
        "isValidTest": 0
        ...
    }
}
    

edit: the JSON can have three different Values with three different Styles.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

0

This is an example of what you could do

Example 1

<Input
    style = 
        {{borderColor: obj.validate.isValidTest === 0 ? 'red':'green'
        boxShadow: `0 0 5px ${obj.validate.isValidTest === 0 ? 'red' : 'green'}`}}
    ...
/>

What's happening here

By utilizing the shorthand conditionals we can apply a borderColor & boxShadow to the style depending on the value of isValidTest within obj (which will be replaced by the name of your object)(!!)

Have a look at this example to see what is happening here

NOTE Ofcourse, this could be separated from the inline style attribute by setting a className depending on the outcome of isValidTest or by applying a different style constant to it depending on the same conditional

Example 2

const errorStyles = {
  borderColor: 'red',
  boxShadow: '0 0 5px red'
}
const validStyles = {
  borderColor: 'green',
  boxShadow: '0 0 5px green'
}

<Input
    style={ obj.validate.isValidTest === 0 ? errorStyles : validStyles }
/>

Again, in this sandbox both examples are shown in the same file, on the same page.

You could also have a look at this question & answer for more examples and information

EDIT

To account for more than two values in isValidTest you could go at it like so:

const errorStyles = {
  borderColor: 'red',
  boxShadow: '0 0 5px red'
}
const validStyles = {
  borderColor: 'green',
  boxShadow: '0 0 5px green'
}
const error2Styles = {
  borderColor: 'magenta',
  boxShadow: '0 0 5px magenta'
}
const valid2Styles = {
  borderColor: 'yellow',
  boxShadow: '0 0 5px yellow'
}


isValid = (valid) => {
    switch(valid) {
      case -1:
        return errorStyles
        break;
      case 0:
        return error2Styles
        break;
      case 1:
        return validStyles
        break;
      case 2:
        return valid2Styles
        break;
   }
}


<Input
    style={this.isValid(obj.validate.isValidTest)}
/>

What happens in the above example

As seen above the style attribute refers to this.isValid which in turn return a const containing the styles, supplied to this function is the isValidTest property from your obj.validate.

I have updated the sandbox to include the above example

Hope this helps!

Mike Donkers
  • 3,589
  • 2
  • 21
  • 34