japgolly / scalajs-react Goto Github PK
View Code? Open in Web Editor NEWFacebook's React on Scala.JS
Home Page: https://japgolly.github.io/scalajs-react/
License: Apache License 2.0
Facebook's React on Scala.JS
Home Page: https://japgolly.github.io/scalajs-react/
License: Apache License 2.0
This is a silly one : )
React won't honor the "for" attribute on vdom labels, but does provide "htmlFor" which renders as a "for" element.
label(`for`.attr := p.name, className := "control-label", l) // doesn't work
label("htmlFor".attr := p.name, className := "control-label", l) // works
Easy fix would be to add "for" -> "htmlFor" to the attrTranslations map in VDomBuilder.scala
More info: facebook/react#310
I am trying to port the the URI library testing code to scalajs-react and I get the following error with the most simple hello world I am trying to put together to get going.
It says in red at the bottom:
GET file:///home/golly/projects/scalajs-react/core/src/main/scala/japgolly/scalajs/react/ReactComponentB.scala net::ERR_FILE_NOT_FOUND
which seems like it is a problem even if I would not be surprised that there is a problem with my setup somehow too...
Is there any support for mixins? I am making some behaviour that would cross cut components and mixins would be the perfect fit. I didn't find any mention of it in the docs or code.
I am referring to mixins from here:
http://facebook.github.io/react/docs/reusable-components.html#mixins
Don't forget, future-Me.
Candidates of usefulness:
.focusState
ReactST.zoom
ReactTestUtils.renderIntoDocument
doesn't accept a ReactElement
but should.
> var div = React.createElement("div", null, "Hello ")
ReactElement {type: "div", key: null, ref: null, _owner: null, _context: Object…}
> var d2 = React.render(div, root)
ReactDOMComponent {_tag: "div", tagName: "DIV", props: Object, _owner: null, _lifeCycleState: "MOUNTED"…}
> d2.refs
undefined
React.createElement: String => ReactDOMElement <: ReactElement
React.render: ReactDOMElement => ReactDOMComponent
Hi ,
now a days people are talking about encapsulating style inside components itself ..
https://github.com/js-next/react-style ,etc
any chance to have same thing in our world ?
val localStyle = Map( color -> '"red", paddingBottom -> "10px" ,backgroundColor -> Props.bg)
div(style := localStyle)
Hi guys,
When following the instructions to build the examples, I get a bunch of similar errors on all examples. Here's one of them, in ExperimentSamples:
[error] D:\dev\scalajs-react\gh-pages\src\main\scala\ghpages\ExperimentExamples.
scala:25: type mismatch;
[error] found : Long
[error] required: japgolly.scalajs.react.vdom.ReactVDom.Modifier
[error] (which expands to) scalatags.generic.Modifier[japgolly.scalajs.reac
t.vdom.VDomBuilder]
[error] Note that implicit conversions are not applicable because they are ambig
uous:
[error] both method longFrag in trait Aggregate of type (v: Long)japgolly.scala
js.react.vdom.ReactVDom.all.Frag
[error] and method reactNodeAsDomChild in trait Aggregate of type [T](c: T)(imp
licit evidence$2: T => japgolly.scalajs.react.ReactNode)japgolly.scalajs.react.v
dom.ReactVDom.all.Modifier
[error] are possible conversion functions from Long to japgolly.scalajs.react.v
dom.ReactVDom.Modifier
[error] .render((_,s,_) => div("Seconds elapsed: ", s))
I've tried building the examples with one of the tags and I get the same error. Note that, prior to the errors, I get the following warning
[warn] Scala version was updated by one of library dependencies:
[warn] * org.scala-lang:scala-library:(2.10.2, 2.10.0) -> 2.10.4
[warn] To force scalaVersion, add the following:
[warn] ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }
[warn] Run 'evicted' to see detailed eviction warnings
Is any of the scalajs-react dependencies referring old scala versions? Could you please lend me a hand?
Thanks!
somewhere between 0.2.0
and 0.2.1-SNAPSHOT
something got lost with propagating the key property. Take a look at this example, react says I am not passing the key property through.
val ApplicationItem = ReactComponentB[PApplication]("ApplicationItem")
.render(P => {
tr(key := P.id)(td(P.name), td(P.description), td(P.url))
}).create
....
val App = ReactComponentB[Seq[PApplication]]("ApplicationTable")
.initialState(ApplicationStore.allApps())
.backend(new AppBackend(_))
.render { (P, S, B) =>
val body: Modifier = if (S.isEmpty) tr(key := "empty-state")(td(colSpan := "3")("Empty!"))
else S.map(f => ApplicationItem(f))
div(cn := "block-flat")(
div(cn := "content")(
table(cn := "no-border table-condensed")(
thead(cn := "no-border")(
tr(th("Name"), th("Description"), th("URL"))
),
tbody(cn := "no-border-x no-border-y")(
body
)
)
)
)
}.create
Now if I do this, it works. This is a pretty common pattern, but I am not entirely sure how to fix it, there is a lot of implicits to track down to figure out what's going on.
val App = ReactComponentB[Seq[PApplication]]("ApplicationTable")
.initialState(ApplicationStore.allApps())
.backend(new AppBackend(_))
.render { (P, S, B) =>
val body: Modifier = if (S.isEmpty) tr(key := "empty-state")(td(colSpan := "3")("Empty!"))
else S.map(f => tr(key := f.id)(td(f.name), td(f.description), td(f.url)))
div(cn := "block-flat")(
div(cn := "content")(
table(cn := "no-border table-condensed")(
thead(cn := "no-border")(
tr(th("Name"), th("Description"), th("URL"))
),
tbody(cn := "no-border-x no-border-y")(
body
)
)
)
)
}.create
Thanks for taking a look/giving advice.
Master fails due to differences in implicit resolution between Scala 2.11 and 2.10.
Scala's implicit resolution is trouble enough without juggling two sets of rules.
Strongly leaning towards dropping Scala 2.10 support. Can't see any apps in prod originally in 2.10 that need to and can afford to upgrade scalajs-react but can't afford to upgrade Scala.
def render: ReactElement
.renderableBackend
/ .backendRenderable
/ .backendR
or something to ReactComponentB
. Could even be crazy and use implicits + dep types to have it be just .render
and auto-wire .render
.Hi i am trying crete a method that i can use on any components which should go away when mouse is clicked other part of DOM .
i was trying to implement this way
trait OnClickAwaybale {
def onClickAway
}
class LBackend( t: BackendScope[_,_]) extends OnClickAwaybale {
override def onClickAway: Unit = println("you killed me! ")
}
val clickListener = ReactComponentB[Unit]("clickMe")
.stateless
.backend(new LBackend(_))
.render((P,S,B) => {
<.div("dude")
})
.configure(clickAwayMixin)
.buildU
def clickAwayMixin[P,S,B] = (c:ReactComponentB[P,S,B]) => {
def clickAway(t: ComponentScopeM[_, _, _]): js.Function1[Event, Unit] = {
val b = t.backend.asInstanceOf[OnClickAwaybale]
lazy val listener: js.Function1[Event, Unit] =
(e: dom.Event) => {
val el = t.getDOMNode()
if (el != e.target && !MDom.isDecedant(el, e.target.asInstanceOf[HTMLElement])) {
b.onClickAway
}
}
listener
}
c.componentDidMount(scope => dom.document.addEventListener("click",clickAway(scope)))
.componentWillUnmount(scope => dom.document.removeEventListener("click",clickAway(scope)))
}
listener attached and everything works as expected until unmounted , after component unmounted i still
see listener attached to dom.window and if i click now i am getting the following error
Uncaught Error: Invariant Violation: getDOMNode(): A component must be mounted to have a DOM node.
could any one please help me in this ... ,or is there any other elegant solution for this problem ?
Thank You
Chandra
If your React component's render function is "pure" (in other words, it renders the same result given the same props and state), you can use this mixin for a performance boost in some cases.
Similar to #55
I'm having problems getting class attributes to show up on elements in my play project. I've tested them using a direct clone of the scalajs-react repository with modifications and that works correctly.
I'm at a bit of a loss as to what is going wrong here. I've cloned the play-with-scalajs-example repository and created a scalajs-react branch with an example that does not work correctly.
The key code that doesn't work correctly is here
val HelloMessage = ReactComponentB[String]("HelloMessage")
.render(name => div("Hello there ", name, cls:="someclass", id:="someid"))
.create
React.renderComponent(HelloMessage("John"), document getElementById "scalajsShoutOut")
g.console.log(React.renderComponentToString(HelloMessage("John")))
Repository is here https://github.com/DylanArnold/play-with-scalajs-example/tree/scalajs-react
Testing instructions
git clone https://github.com/DylanArnold/play-with-scalajs-example.git -b scalajs-react
cd play-with-scalajs-example
activator
run
Navigate to http://localhost:9000
Check console for rendered div and note id="someid"
is correct but class="someclass"
is missing
Thanks for a great project. I know this may not exactly be a scalajs-react problem but any ideas would be greatly appreciated
Clarify difference.
When using source maps with scalajs-react, it produces sources which are local to the computer where it has been compiled.
I first opened an issue in scala-js, thinking it was a compiler's issue. The available fix is explained in there: scala-js/scala-js#993
I was curious how you'd approach the following problem: I've been using React-bootstrap for quite some time and was looking to use it with your library. I am still new to fully understanding how your library works, but my thought was to use it similarly to how you use the animation addon. So that would convert something like this to something abbreviated like
case class Button(active: js.UndefOr[Boolean] = js.undefined,
onclick: js.UndefOr[() => Unit] = js.undefined) {
def toJs: js.Object = {
val p = lit("active" -> active)
onclick.foreach(f => p.updateDynamic("onClick")(f))
p
}
def apply(children: js.Any*): ReactComponentU_ = {
val f = ReactBootstrap.Button
f(toJs, js.Array(children.toSeq: _*)).asInstanceOf[ReactComponentU_]
}
}
Again it's abbreviated, assume ReactBootstrap is a dynamic. Also on the apply function I wanted to have bare children, pure text, so I widened whats expected but I didn't spend enough time to try to figure out how all the implicits would help me with narrowing that scope.
Thanks for the help.
-Dan
Opt-out of
setState
modState{,O,U}
state
← technically but this can stay==>
-->
Add:
IO[S]
S ⇒ IO[Unit]
S ⇒ S ⇒ IO[Unit]
ChangeFilter
I just saw you released it GPL, is there any way you can release it under a more permissive license like Apache or BSD? I love the library!
e.key
and e.getModifierState()
propertiesonBeforeInput
eventReact.Children.count
has been added as a helper for counting the number of childrenhttp://facebook.github.io/react/blog/2014/07/17/react-v0.11.html
With its annoying inheritance structure and React needing attributes and styles in different format it would be better to just copy Scalatags into this project, customise and drop the dependency.
Since #2 has been more of a discussion on children properties, I wanted to file a separate issue to talk about how the best way to use third-party components. I define a third party component as something most likely written in JS/JSX which has a defined react interface. Here's what I've been doing so far.
trait ReactBootstrap extends js.Object {
def Modal: js.Dynamic = ???
def Button: js.Dynamic = ???
def OverlayMixin: js.Dynamic = ???
}
case class Modal(title: String,
onRequestHide: () => Unit,
className: js.UndefOr[String] = js.undefined) {
def toJs: js.Object = {
val p = lit(
"title" -> title,
"className" -> className
)
p.updateDynamic("onRequestHide")(onRequestHide)
p
}
def apply(children: VDom*): ReactComponentU_ = {
val f = ReactBootstrap.Modal
f(toJs, js.Array(children.toSeq: _*)).asInstanceOf[ReactComponentU_]
}
}
I don't need to mess with the render function or any other internal logic to the component but I want to be able to use it in my components. This seems to work fine.
Thoughts?
Explain the unfortunately necessary plethora of types. Maybe tables by cluster.
Hi ,
I am trying to port the following jsx code
https://github.com/callemall/material-ui/blob/master/src/js/flat-button.jsx
<Ripple ref="ripple" className="mui-flat-button-ripple" />
<Ripple className="mui-flat-button-focus-ripple" />
how can i achieve this ( ref attributes on components ) in scala-js react ?
Thank You
Chandra
When a component has an array of children, I get the following warning on the console:
Each child in an array should have a unique "key" prop. Check the render method of Experiences. See http://fb.me/react-warning-keys for more information. dashboard-frontend-jsdeps.js:10173
While I can add the key
attribute to scalatags elements, I don't see a way to add attributes to React components themselves.
Mixins are useful mostly because of their ability to hook into the component lifecycle and register / deregister things when a component is un/mounted. http://facebook.github.io/react/docs/reusable-components.html
The example on setTimeout() is a good one - a mixin makes methods available to the equivalent of the Backend methods and also hooks into lifecycle methods i.e. componentWillMount.
Not sure if anyone has any ideas on how to implement this, or if it is needed. I would think at first glance it would involve traits and functional composition for the lifecycle methods but can't figure out a nice way to do it. Another idea was maybe an additional "MixinConfiguration" in ReactComponentB to supplement Backend? It could be passed to the Backend's constructor via BackendScope. buildSpec would then have to set the mixins property of the Dynamic object so that its lifecycle methods are called correctly.
Hopefully that made some sense. Just looking for some feedback on the idea. I'll gladly give implementation a go if anyone else is interested.
(quick guess that may not make sense below)
trait Mixin {
def componentWillUpdate: ...
...
}
trait MixinConfiguration {
def mixins: List[Mixin]
}
class B1[MC <: MixinConfiguration] {
type ScopeB = BackendScope[Props, State, MC]
}
Hi ,
if i pass html text to component ,its rendering as plain text ..,how can i use dangerouslySetInnerHTML in scalajs-react ?
Thank You
Chandra
Can then remove quasi-overloaded methods:
runStateS
_runStateS
runStateFS
_runStateFS
Scalatags is awesome but it's also starting to shit me with extended use. Start making it optimal here and send patches back over the fence later.
Bundle
? Even so, I don't need it to recommend its use.*
is nice but only provides a small subset of tags and attributes.Tag
conflicts in Bundle
and in all
.*
still requires the user to import implicits._
. That's good but 99% of time user would want both, add something that provides both.Bundle.implicits
are way too generic and simple (eg. raw
), and cause conflicts.I am bit puzzled since the setup instructions seem to be very well made, but I need to include
jsDependencies += "org.webjars" % "react" % "0.11.1" / "react-with-addons.js" commonJSName "React"
in my build to get it to work. Had to dig around quite a bit in your Build.scala to find it, and I still believe that I do something wrong. If that is the way it is supposed to work, please add it to the README.
Annoying but easily fixed.
val unusedField: TagMod = (^.cls := "empty")("-") // doesn't work
val zza: TagMod = "-"
val zzb: TagMod = ^.cls := "empty"
val zzc: TagMod = zza ????? zzb
Hi ,
I created new examples layout and gh-pages for scalajs-react . you can checkout changes here
http://chandu0101.github.io/scalajs-react/example/ ( whole app built using scalajs-react -;) )
please let me know if changes are okay ? , i'll send a PR !.
Thank You
Chandra
Warning: Unsupported style property background-color. Did you mean backgroundColor?
From #29 japgolly :
About scrollTo, do other routers do that on every route change?
Also could you please open a new issue if you want to discuss that further? Cheers
Other routers (atleast react-router) resetting scroll position to top for each route transition by default , but they have an option(ignoreScrol...) to override that .. .
nearly forgot
def ~~>?(io: Option [IO[Unit]]): Modifier = io.map(a ~~> _)
Allow initial props to be defined on a react component similar to the js react interface. Instead of caching a props object like in the js version, perhaps use a function that returns the properties.
Then the API for creating an instance from the created class would need to be altered so that you were not forced to provide a properties object.
First of all, I'm quite new both to Scala.js and React.js, so it may actually exist a way of doing what I expose:
I have components that get something that can be rendered as a parameter (for example, a Dropdown component that receives both a trigger that is always rendered and a content that is only rendered when the dropdown is active).
Right now I'm typing those parameters as TypedTag[ReactOutput], as that seems to be the type of tags such as div(), span(), etc.
What I've found is that TypedTag shares no superclass (other than Object/Any) with ReactComponentU, so I can't pass instantiated components directly as "renderable" parameters. While enclosing components in a span() works and is not a great amount of work, I think it would be nice if we could have a way to pass both tags and components directly.
Thanks,
Artur
How would one integrate third-party components such as React Bootstrap (http://react-bootstrap.github.io/components.html) using scalajs-react and its use of scalatags? From what I can gather, you must map every tag you might ever use, is that correct?
Here is a react bootstrap example component:
var buttonsInstance = (
<ButtonToolbar>
{/* Standard button */}
<Button>Default</Button>
{/* Provides extra visual weight and identifies the primary action in a set of buttons */}
<Button bsStyle="primary">Primary</Button>
{/* Indicates a successful or positive action */}
<Button bsStyle="success">Success</Button>
{/* Contextual button for informational alert messages */}
<Button bsStyle="info">Info</Button>
{/* Indicates caution should be taken with this action */}
<Button bsStyle="warning">Warning</Button>
{/* Indicates a dangerous or potentially negative action */}
<Button bsStyle="danger">Danger</Button>
{/* Deemphasize a button by making it look like a link while maintaining button behavior */}
<Button bsStyle="link">Link</Button>
</ButtonToolbar>
);
If I wanted to use this component in scalajs-react, what would I have to do?
I have just started to use scalajs-react (and like it a lot so far). I am, however, running into an issue of <input>
component losing focus after every edit. I am using withKey()
as described in the scalajs-react documentation (that was the first suspect).
Here is a minimal example to reproduce the issue:
package example
import org.scalajs.dom
import dom.HTMLInputElement
import scala.scalajs.js
import js.annotation.JSExport
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.ReactVDom._
import all._
@JSExport
object ScalaJSExample extends js.JSApp {
def main(): Unit = {
val Examples = ReactComponentB[Unit]("examples")
.initialState(IndexedSeq("first", "second"))
.backend(new ExampleBackend(_))
.render((_,state,backend) => {
val Elements = state.zipWithIndex.map{case(v, index) => {
val Example = ReactComponentB[String]("Example").render(v =>
input(value := v, onchange ==> backend.onChange(index))).build
Example.withKey(s"key$index")(v)
}}
div(Elements)
}
).build(())
React.renderComponent(Examples, dom.document.getElementById("playground"))
}
}
class ExampleBackend(t: BackendScope[Unit, IndexedSeq[String]]) {
def onChange(index:Int)(e: SyntheticEvent[HTMLInputElement]) =
t.modState { old =>
old.updated(index, e.target.value)
}
}
If I replace,
val Example = ReactComponentB[String]("Example").render(v =>
input(value := v, onchange ==> backend.onChange(index))).build
Example.withKey(s"key$index")(v)
with a direct <input>
component, all is well. But in a real example, I may not be able to do so.
input(value := v, "key".attr := s"key$index", onchange ==> backend.onChange(index))
Note that the equivalent Javascript code work fine (I made sure that I use the same 0.11.2 version):
/** @jsx React.DOM */
var Example = React.createClass({
render: function() {
return <input value={this.props.text} onChange={this.props.onChange}/>;
}
})
var Examples = React.createClass({
getInitialState: function() {
return {items: ["first", "second"]};
},
handleChange: function(index, e) {
this.state.items[index] = e.target.value;
this.setState({items: this.state.items});
},
createItem: function(itemText, index) {
return <Example text={itemText} key={index}
onChange={this.handleChange.bind(this, index)}/>;
},
render: function() {
return <div>{this.state.items.map(this.createItem)}</div>;
}
});
React.renderComponent(
<Examples/>,
document.getElementById("container")
);
Is there an issue with how I have arranged or is this a bug in scalajs-react?
Is there a sbt template project available on gibthub that i can just check out and run in order to get started quickly with scalajs-react?
Like #17, but for
The Scalaz modules aren't referenced in the readme, nor are there any examples.
if one wants to read files locally in JavaScript one can do it as follows:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
console.log("received text");
var test = akka.http.test.SpeedTest();
console.log(test)
test.analyse(reader.result);
console.log("done")
}
reader.readAsText(file);
} else {
console.log("problem")
fileDisplayArea.innerText = "File not supported!"
}
});
}
The latest scalajs-dom allows one to create a FileReader object. After changing the version of scalajs-dom
to 0.7-SNAPSHOT
:
"org.scala-lang.modules.scalajs" %%% "scalajs-dom" % "0.7-SNAPSHOT"
one can get the following to works - but does not look very functional.
val fileInput = ReactComponentB[String]("FileInput")
.render{s =>
println("hello")
def handleChange(e: SyntheticEvent[HTMLInputElement]) = {
val textType = "text.*".r;
for {
i <- 0 to e.target.files.length - 1
file = e.target.files(i)
// if !textType.findPrefixMatchOf(file.name).isEmpty
} yield {
val reader = new FileReader()
reader.onload = { e: UIEvent =>
println("loaded="+reader.result)
}
reader.readAsText(file)
println(file.name)
}
}
input( `type`:="file",onchange==>handleChange)(s)
}
React.renderComponent(fileInput.create("hi"),mountNode)
I was trying to work out if the reader.onload
is something that should be processed via React's Synthetic Events. What would be the correct way to do this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.