Component Variables


(Gleb Dolzhikov) #1

During last code review i invent maybe reinvent some interesting approach that could be helpful for others.
Minimal example of it here: https://codepen.io/Kinosura/pen/LOoNxY

In our app it looks like so :

import Add from "material-ui/svg-icons/content/add";
import Remove from "material-ui/svg-icons/content/remove";
.... 
render(){
 let Button = Add;
 If(someCond){
  Button = Remove
 }
 return(
  <IconButton>
    <Button className="some-cute-class" onClick={createUnicorn}/>
  </IconButton>
 )
}

Any ideas about it? i think looks pretty clear


(Gio Logist) #2

The only problem I can see is from a readability standpoint. I would recommend doing one of the following:

A ) Create a new variable (AddOrRemove), which isn’t a component, but rather gets assigned the Add or Remove component
B ) Make that a separate component altogether

Then, your code becomes much easier to read at just a quick glance.


(Christian Andersson) #3

Neat approach, but I would personally not use this because it is not directly clear which component you are rendering because Button is not a component on its own.

I would just keep it simple:

render(){
 return(
  <IconButton>
    {comeCond
      ? <Remove className="some-cute-class" onClick={createUnicorn} />
      : <Add className="some-cute-class" onClick={createUnicorn} />
  </IconButton>
 );
}

I find this a bit more readable.


(Gleb Dolzhikov) #4

The main idea behind this, that props stay the same and don’t duplicated. maybe ?: expression and addorremove name fit the most