This is from the table example from React-toolbox (which could use a tag)
class TableTest extends React.Component {
state = { selected: [], source: users };
handleSelect = (selected) => {
this.setState({selected});
};
render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source}
/>
);
}
}
This does not compile with webpack/babel for me but the following 'correct' Javascript does. Is this JSX notation and a sign that I'm not transpiling JSX as I think I am?
class TableTest extends React.Component {
constructor() {
super();
this.state = { selected: [], source: users };
this.handleSelect = (selected) => {
this.setState({selected});
};
}
render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source} />
);
}
}
Webpack/babel chokes on:
ERROR in ./src/client/app/app.jsx
Module build failed: SyntaxError: Unexpected token (21:8)
19 |
20 | class TableTest extends React.Component {
> 21 | state = { selected: [], source: users };
This is using class properties, which are currently part of Babel's stage 2 preset.
For this code, the = statements in the class body would get moved into the constructor by the class properties transform.
Here's the original code in the Babel REPL with suitable presets applied.
You will need to add this preset (or a lower stage preset, as all Babel stage presets also include higher stage features) to your Babel config, or add the transform plugin to it individually.
Example Babel config which would provide all the features you need to transpile the original code:
{
presets: ['es2015', 'react', 'stage-2']
}
It's throwing an error on the = declaration inside of the class. You need to bind this to handleSelect due to React's no autobinding rule.
https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
class TableTest extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: [], source: users
};
this.handleSelect = this.handleSelect.bind(this);
}
handleSelect(selected) {
this.setState({selected});
}
render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source}
/>
);
}
}
Related
I can't seem to get theme working with LitElement. I can set the other props of setup no problem, but the theme doesn't get recognized by Twind. It's also worth mentioning that I get no error when compiling. Anyone have a quick solution?
import {LitElement, html} from 'lit';
import {setup, warn, create, cssomSheet} from 'twind';
setup({
mode: warn,
theme: {
colors: {
purple: '#2013',
},
},
});
const sheet = cssomSheet({target: new CSSStyleSheet()});
const {tw} = create({sheet});
export class MyApp extends LitElement {
static styles = [sheet.target];
static get properties() {
return {
name: {type: String},
};
}
constructor() {
super();
this.name = 'World';
}
render() {
return html` <h1 class="${tw`text(3xl purple)`}">${this.name}!</h1> `;
}
}
window.customElements.define('my-app', MyApp);
Probably, the problem is the shadow-dom.
If you can use Twind, you can try to render to light-dom, instead shadow-dom.
To use light-dom add in your web-component class this method:
createRenderRoot() {
return this;
}
In other hand, I don't sure it works without Lit...
I'm developing an angular app.I will demonstrate the problem using small code snippets for clarity.
My Component
export class MyComponent extends BaseComponent {
isuserActive = false;
...
}
Base Component
export class BaseComponent {
...
constructor() {
this.route.data.subscribe((values: Object = {}) => {
this['isuserActive'] = values['isuserActive'];
...
});
...
}
}
Routes
... data { isuserActive: true, ...
But finally when I check MyComponent, its isuserActive is false which is wrong.
But it works fine (isuserActive is true) when my component is as follows (that I don't prefer).
My Component
export class MyComponent extends BaseComponent {
isuserActive; // no initial value (I don't prefer this way)
}
So how can I solve this.
This question already has answers here:
React Js conditionally applying class attributes
(24 answers)
Closed 6 years ago.
My state is {visibilityFilter: "completed"} or {visibilityFilter: "todo"}. Based on this I want to assign classnames to an element. Something like this,
<span {this.state.visibilityFilter=="completed"?className="active":className:""}>Completed</span>
But it's not working. I tried different variations of it,
{<span this.state.visibilityFilter=="completed"?className="active":className:"">Completed</span>}
But none of them are working. I know that it can work if I create a variable outside return statement and assign it in HTML. Like this,
let classCompleted = this.state.visibilityFilter == "completed"? "active":"";
and then,
<span className={`$(classCompleted)`}></span>
But I want to know how to do evaluate class in return statement.
You're close, you just put the className part outside:
<span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter.bind(this,'completed')}>Completed</span>
Off-topic side note:
Using bind in the onClick every time means you'll re-bind every time that element is rendered. You might consider doing it once, in the component's constructor:
class YourComponent extends React.Component {
constructor(...args) {
super(...args);
this.handleFilter = this.handleFilter.bind(this);
// ...
}
handleFilter() {
// ...
}
render() {
return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
}
}
Another option is to make it an arrow function, if you've enabled class properties in your transpiler (they're in the stage-2 preset in Babel as of this writing, January 2017):
class YourComponent extends React.Component {
// ...
handleFilter = event => {
// ...
};
render() {
return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
}
}
Live example of that one:
class YourComponent extends React.Component {
constructor() {
super();
this.state = {
visibilityFilter: ""
};
}
handleFilter = event => {
this.setState({
visibilityFilter: "completed"
});
};
render() {
return <span className={this.state.visibilityFilter == "completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
}
}
ReactDOM.render(
<YourComponent />,
document.getElementById("react")
);
.active {
color: blue;
}
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Use classNames, A simple javascript utility for conditionally joining classNames together.
Note: I've added the state and todo classes to demonstrate working with multiple classes. btw - the comments are not valid JSX, so don't use the code as is.
<span className={
state: true, // always
active: this.state.visibilityFilter === "completed", // conditional
todo: this.state.visibilityFilter !== "todo" // conditional
}>
Completed
</span>}
Example (based on T.J. Crowder`s code):
class YourComponent extends React.Component {
constructor() {
super();
this.state = {
visibilityFilter: ""
};
}
handleFilter = event => {
this.setState({
visibilityFilter: "completed"
});
};
render() {
return (
<span className={classNames({
state: true,
active: this.state.visibilityFilter === "completed"
})} onClick={this.handleFilter}>Completed
</span>
);
}
}
ReactDOM.render(
<YourComponent />,
document.getElementById("react")
);
.state {
color: red;
cursor: pointer;
}
.active {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.5/index.min.js"></script>
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
I am implementing the Class extend and i get this error Missing class properties transform.
The Component was
import React from ('react')
const Manna = React.createClass({,
initVal: {
likes: 10,
}
render() {
// code
return {
// code
}
}
});
module.exports = Manna
and changed to
import React from 'react';
export default class Manna extends React.Component {
InitVal: {
likes: 10
}
render() {
// code
return {
// code
}
}
};
This is my configuration in webpack.config.dev.js
{
test: /\.js$/,
loaders: 'babel?presets[]=react,presets[]=es2015,presets[]=stage-0',
include: path.join(__dirname, 'client')
},
I have changed the loader following this answer
Before it was loaders: ['babel']
I have also added to .babelrc the plugin
["transform-class-properties"],
This is the error in the console
Missing class properties transform.
15 | // },
16 |
> 17 | InitVal: {
| ^
18 | likes: 10,
19 | code: "2",
20 | size: 350,
I do not understand why it is complaining now for Missing class properties transform, what is wrong in the component?, everything was working fine before of these changes
Here a gist with the full React component
Try with =
import React from 'react';
export default class Manna extends React.Component {
InitVal = {
likes: 10
}
render() {
// code
return {
// code
}
}
};
Check this
UPDATE
Since we are using stage-0 and transform-class-properties is included in stage-2, we don't have to include it manually in .babelrc under plugins. The following configuration works fine: "presets": ["es2015", "stage-0", "react"].
In the gist at line 5 InitVal is written with an uppercase i while at line 39 is written with a lowercase i: initVal. Additionally render method returns an Object Literal, which is invalid, a single child element as to be returned as explained here.
Here is the official documentation for react components defined as es6 classes.
I want to implement the following functionality https://facebook.github.io/react/tips/expose-component-functions.html, but I use ES6 syntax
#controllable(['center', 'zoom', 'hoverKey', 'clickKey', 'selectedCountry'])
export default class ContactMapView extends Component {
constructor(props) {
super(props);
this.initialFunc = this.initialFunc.bind(this);
}
initialFunc() { … }
When I call initialFunc in my parent class
componentDidMount() {
MapStore.addChangeListener(this._onChange.bind(this));
this.refs['mapView'].initialFunc();
};
I get the following error:
TypeError: this.refs.mapView.initialFunc is not a function
Any ideas how could I run function of my child Component?