Skip to content

Shorter prop usage syntax  #20

Open
@labe-me

Description

@labe-me

Hello,

I've been using the project for some days and was really pleased by the lib except for the syntax part which suffer from react/js legacy.

The problem with Props() is that it forces you to type a lot of things and when you start to use apply(...) = apply(Props(...)) you have to type three times your parameters to keep things in sync which is a pain.

I just found a method to shorten the syntax but I haven't tested it a lot so your comments are welcome :

// This is our Props()
case class UserRankingLine(pos:Int, name:String, image:String, score:String)

// A component to display a Ranking
object UserRankingLine extends TypedReactSpec {
  // our Props is the case class
  type Props = UserRankingLine
  // this implicit will run the .apply(o:Props) whenever a Props() needs to be converted into a ReactDOM
  implicit def toReactDOM(o:Props) : ReactDOM = apply(o)

  // our state as usual
  case class State()
  def getInitialState(self:This) = State()

  // render the component
  @scalax def render(self:This) = {
    <div className="UserRankingLine">
      <div className="rank">{ self.props.pos }</div>
      <img src="{self.props.image}" alt="" width="50" height="50" />
      <div className="name">{ self.props.name }</div>
      <div className="score">{ self.props.score }</div>
    </div>
  }
}

And then you can instantiate your component just like with the regular Component.apply(...) method :

@scalax def render(self:This) = {
  UserRankingLine(1, "User", "img/foo.png", "1000 pts")
}

Maybe the implicit can be pushed up into the hierarchy so users don't have to type it everytime or maybe the case class type could be given as a generic parameter so the implicit could be created inside the TypedReactSpec[T]. I am not sure what could work with the project.

There may be problems with Seq[Component], I am not sure implicits will be run correctly to get Seq[ReactDom], I haven't tested it yet and you may see problems coming :)

Anyway thank you for the awesome work and I hope this little trick will be of some help to simplify the API.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions