0

I have a React Input component, and I want it to display an error icon if a condition is true. Currently I achieve it through an if condition that renders a component with the icon when the condition is true, and another component without it otherwise:

   if (field_meta.error) {
      return (
        <FormControl fullWidth margin="normal">
          <InputLabel style={{color: "red"}} htmlFor={field_meta.name}>{field_meta.title}</InputLabel>
          <Input
            id={field_meta.name}
            defaultValue={field_meta.value? field_meta.value: ""}
            onChange={this.handleChange}
            margin="normal"
            startAdornment={  // ***** This is the props that depends on the condition
              <InputAdornment position="start">
                <i style={{color: "red"}} className="zmdi zmdi-alert-circle zmdi-hc-fw"/>
              </InputAdornment>
            }
          />
          <FormHelperText style={{color: "red"}}>{field_meta.error}</FormHelperText>
        </FormControl>
      )
    } else {
        return (
            <FormControl fullWidth margin="normal">
                <InputLabel htmlFor={field_meta.name}>{field_meta.title}</InputLabel>
                <Input
                  id={field_meta.name}
                  defaultValue={field_meta.value? field_meta.value: ""}
                  onChange={this.handleChange}
                  margin="normal"
                />
            </FormControl>
        )
    }

I think there must be a more efficient way for doing this without rendering two complete different components depending on the condition, probably by conditioning the inclusion of the specific props only, but I can't find how to do so.

1 Answer 1

1

Of course. You can do it with short circuiting:

 <FormControl fullWidth margin="normal">
          <InputLabel style={field_meta.error && {color: "red"}} htmlFor={field_meta.name}>{field_meta.title}</InputLabel>
          <Input
            id={field_meta.name}
            defaultValue={field_meta.value? field_meta.value: ""}
            onChange={this.handleChange}
            margin="normal"
            startAdornment={  field_meta.error && (
              <InputAdornment position="start">
                <i style={{color: "red"}} className="zmdi zmdi-alert-circle zmdi-hc-fw"/>
              </InputAdornment>)
            }
          />
          {field_meta.error && <FormHelperText style={{color: "red"}}>{field_meta.error}</FormHelperText>}
</FormControl>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.