Default values of props in ReactJS - reactjs

How can I define default values in ReactJS?
var Header = React.createClass({
render: function() {
return (
<h1>{this.props.title} if not defined insert "Title"</h1>
)
}
});
I extremely increased my React skill and as of 2018 this example (I
wrote at the question body) is outdated. You should do it like
#VladyVeselinov shown at the picture using ES6 classes and babel
transforms like babel-class-properties that allow you to make static
fields for your components

Since your example uses the createClass version of creating a component, you can use the getDefaultProps function.
https://facebook.github.io/react/docs/react-without-es6.html#declaring-prop-types-and-default-props
getDefaultProps: function() {
return {
title: 'Title'
};
}

Related

React state - what I am doing wrong?

I am trying to learn reactjs and building small app that takes in names and then shows the names..
I have an input form, and I am able to get data from input form after clicking submit into my state object called names.
however I am stuck on passing the state from the parent to another component that is inside of my ShowNames component:
So, in App, I am doing this render:
render : function() {
return (
<div>
<InputName addToState={this.addToState}/>
<ShowName renderName={this.renderName}/>
</div>
)
}
});
Then ShowName component has following:
var ShowName = React.createClass({
render : function() {
return (
<ListOfNames renderName={this.props.renderName}/>
)
}
});
So I made
var ListOfNames = React.createClass({
render : function() {
return (
<ul renderName={this.props.renderName}>
{Object.keys(this.state.names).map(this.renderName)}
</ul>
)
}
});
But the issue is it says Cannot read property 'names' of null. Can someone help?
You need to initialise the state otherwise the state will be null.
React.createClass({
getInitialState: function() {
return { names: [] };
},
// all the rest here
}
EDIT
after seeing the code I noticed a couple of errors, the updated code is now here: http://jsbin.com/sewoxu/edit?js,output
So what the main error was that the render function of ShowName was using the state to get the names, but the names where passed via property:
<ShowName renderName={this.renderName} names={this.state.names}/>
so in this case to access the names attribute you need to do:
this.props.names
Also in the example I have moved the renderName function inside the ShowName component.
Hope this helps :)

ReactJS: best practice access input values when creating forms

I've been playing a bit with ReactJS and am really enjoying the framework.
I'm also trying to follow the rule of creating components that are stateless where possible.
I have a Settings component that includes a child SettingsForm and a SettingsWidget.
Settings holds all the states, and only pass it as props to the form and widget.
This works (and scales) well because when the state in Settings is updated, it propagates to all child components.
var Settings = React.createClass({
getInitialState: function() {
settings: {}
}
})
What I am not 100% sure on is the best practice when accessing input values on SettingsForm to pass it on to the parent component.
I know I can use refs and also two-way binding to accomplish this, but neither feel very "ReactJS-like".
Is there a better of way accomplishing this that I am unaware of? For the sake of completeness, I've included the relevant code in my SettingsForm component below
var SettingsForm = React.createClass({
getInitialState: function() {
return {
changed: false
}
},
handleChange: function(event) {
this.setState({changed: true})
this.props.handleChange(
this.refs.emailInputFieldRef.getDOMNode().value,
this.refs.firstNameInputFieldRef.getDOMNode().value
)
},
handleSubmit: function(event) {
event.preventDefault();
// Access and pass on input values to parent callback so state is updated
this.props.handleUpdate(
this.refs.emailInputFieldRef.getDOMNode().value,
this.refs.firstNameInputFieldRef.getDOMNode().value
)
this.setState(this.getInitialState());
},
...
}
For now there is a Mixin you can use to link the input values to the state, called LinkedStateMixin that is exactly what you are looking for...
var WithLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {message: 'Hello!'};
},
render: function() {
return <input type="text" valueLink={this.linkState('message')} />;
}
});
Then all you have to do is modify your handler functions on the parent component to take your inputs as variables, and pass that function down to the child component as a prop. When you want to handle the form, call that function in the props and send the state (bound with from the Mixin) as the variables.
React Docs - React Link

Difference between ReactClass and ReactComponent?

In the React Dom Terminology, what is the difference between ReactClass and ReactComponent?
Simply put:
ReactClass: A model or a shape for components, if you want to create a component called DatePicker, the shape is the ReactClass, not each of the individual components/instances will you create based on that shape.
var MyComponent = React.createClass({
render: function() {
...
}
});
ReactComponent or ReactElement: A component instance that you create based on a pre-defined ReactClass. If you create a component called DatePicker, each instance of that component that is rendered is a ReactElement
var component = React.createElement(MyComponent, props);
Normally you don't use React.createElement because you can just use something like this <MyComponent />, but it's really useful if you want to dynamically create instances of components, like for storing in a variable and rendering them later.
I just found it from my link.
I keep this question for someone who may have the same question.
From React Components,
A ReactComponent Class is simply just a JavaScript class (or "constructor function").
var MyComponent = React.createClass({
render: function() {
...
}
});
When this constructor is invoked it is expected to return an object with at least a render method on it. This object is referred to as a ReactComponent.
var component = new MyComponent(props); // never do this

When should I use getInitialState in a React component

I have a React component that toggles a className when the component is clicked
var Foo = React.createClass({
getInitialState: function() {
return {className: ''}
},
render: function(){
var className = 'bar ' + this.state.className
return React.createElement('div', {className: className, onClick: this.onClick})
},
onClick: function() {
this.setState({className: 'baz'})
}
});
It works fine, but when I am rendering the app server side, I get the following error
Warning: getInitialState was defined on a component, a plain JavaScript class.
This is only supported for classes created using React.createClass.
Did you mean to define a state property instead?
My build step is setup like so
var Foo = require('./Foo');
var factory = React.createFactory(Foo);
module.exports = React.renderToString(factory({}));
Why is what I am doing wrong, and how should it be done?
I am not sure if this helps, but while using fluxible, this is the syntax i used with JSX as part of require component
var app = new Fluxible({
component: React.createFactory(require('./Components/startup.react.jsx'))
});

Using x-editable with reactjs, how to call editable function on items?

I am new to ReactJS, I am trying to create a Reactjs component that is a list of editable fields using x-editable.
According to x-editable documentation I need to call .editable() for each field, normally this is done accessing the element with jQuery.
How can I do it with React ? It has to be done when the component is mounted and I can't find a way to know when the component is rendered...
I would like to know the best way to achieve this ; I had a look at React refs but I am not sure it can help. So I ended up giving it a specific class, then using a selector
to call editable() on the fields, but it works only when the rendering has been done
and I don't find it very elegant.
JS(X) code:
var EditableField = React.createClass({
render: function() {
return <p>{this.props.name}: {this.props.value}</p>
}
});
in script code:
$(document).ready(function() {
$.fn.editable.defaults.mode = 'inline';
$(".editable_field").editable();
You should do it in the componentDidMount function. This function is called when the component is mounted and the DOM is ready. Read more about the lifecycle here: http://facebook.github.io/react/docs/component-specs.html
Example (using refs instead of class selector):
var EditableField = React.createClass({
componentDidMount: function() {
$(this.refs.editable.getDOMNode()).editable()
},
render: function() {
return <p>{this.props.name}: {this.props.value}</p>
}
});
Note that many "jquery plugins" will do heavy DOM manipulations and that does not always play well with React.
You can use react-x-editable(react version of x-editable).Currently not all option supported.I will try to support most of options.

Resources