I have code that is at present accessing a React component directly, and getting a warning saying "You probably don't want to do this." The code is:
var description = document.getElementById('description').value;
console.log(description);
new_child.setState({
description: description
});
The component it's trying to access is:
var that = this;
return (
<table>
<tbody>
{that.state.children}
</tbody>
<tfoot>
<td>
<textarea className="description"
placeholder=" Your next task..."
onChange={that.onChange}
name="description"
id="description"></textarea><br />
<button onClick={that.handleClick}
id="save-todo">Save</button>
</td>
</tfoot>
</table>
);
What is an idiomatic way to replace the code I have here with a "thinking in React" replacement?
You should be using the refs attribute.
So lets say you have a render method that looks like this:
render: function () {
<MyTextBox ref="myText" />
<div>Some other element</div>
}
Now lets say the rendered MyTextBox element has a expode() method. You could call it using:
this.refs.myText.explode()
Essentially, refs has a property myText on it because during render, you provided a ref name to it by writing ref="myText"
You can find more info here
I'd call myself a complete novice here but looking at this code
https://github.com/abdullin/gtd/blob/master/web/components/TaskComposer.jsx
You should be able to bind to the textareas value:
<textarea id="description"
value={that.state.text} ...
and then you can pull out the value in your click handler like this:
var description = this.state.text;
Let me know if this works :)
UPDATE
Just looked at the React home-page (https://facebook.github.io/react/) and the 3rd example An Application seems to follow this pattern as well
var TodoList = React.createClass({
render: function() {
var createItem = function(itemText, index) {
return <li key={index + itemText}>{itemText}</li>;
};
return <ul>{this.props.items.map(createItem)}</ul>;
}
});
var TodoApp = React.createClass({
getInitialState: function() {
return {items: [], text: ''};
},
onChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var nextItems = this.state.items.concat([this.state.text]);
var nextText = '';
this.setState({items: nextItems, text: nextText});
},
render: function() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.onChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}
});
React.render(<TodoApp />, mountNode);
So to answer you're question I think the React way to do stuff is to bind to this.state.
Related
I am using the react-rails gem. In my component I have two input fields with a ref each. However, the console throws me the following error:
Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have
refs. You might be adding a ref to a component that was not created
inside a component's render method, or you have multiple copies of
React loaded
Facebook's documentation does not help.
_new_item.js.jsx
var NewItem = React.createClass({
handleClick() {
var name = this.refs.name.value;
var description = this.refs.description.value;
console.log('The name value is ' + name + 'the description value is ' + description);
},
render() {
return (
<div>
<input ref='name' placeholder='Enter the name of the item' />
<input ref='description' placeholder='Enter a description' />
<button onClick={this.handleClick}>Submit</button>
</div>
);
}
});
_body.js.jsx
var Body = React.createClass({
render() {
return (
<div>
<NewItem />
<AllItems />
</div>
);
}
});
_main.js.jsx
var Main = React.createClass({
render() {
return (
<div>
<Header />
<Body />
</div>
);
}
});
I really don't know where the error is.
You'll better use the function refs instead of the named refs:
So instead of
<input ref='name' />
You can use:
<input ref={node => this.nameElement = node} />
And then instead of:
this.refs.name
Use
this.nameElement
I believe it will fix your problem.
I am trying to save a user's input by using the onChange method described here: https://facebook.github.io/react/docs/forms.html.
I have this line of code for my input:
<input type="text" onChange={this.changeTitle} ref="title" value={this.props.quiz ? this.getTitle() : ''}></input>
However, when I call this.refs.title.value after pressing the spacebar, the space is not registered. Is there anyway I can register this space?
Something as
var ChangeValue = React.createClass({
getInitialState() {
return { currentValue: '' };
},
onValueChange: function (evnt) {
this.setState({ currentValue: evnt.target.value });
},
render: function() {
return (
<div>
<input type="text" onChange={this.onValueChange} />
<p>
Current value is: <b>{this.state.currentValue}</b>
</p>
</div>
);
}
});
React.render(<ChangeValue />, document.body);
Just change onValueChange method to do what you need.
Live example: http://jsbin.com/xayowaloxa/edit?html,js,output
I'am creating component with input element and button element.
I need to get the input value and use with button, for example. How can I do that?
Here's my code:
var InputSearch = React.createClass({
getInitialState: function() {
return {
value: 'pics'
}
},
handleChange: function() {
this.setState({
value: event.target.value
});
},
render: function() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange} />
)
}
});
var ButtonSearch = React.createClass({
handleClick: function(event) {
console.log(this.state.value); // here's go the input value
},
render: function() {
return (
<button onClick={this.handleClick}>GO! </button>
)
}
});
var Search = React.createClass({
render: function() {
return (
<div>
<InputSearch />
<ButtonSearch />
</div>
)
}
});
React.render(
<Search />,
document.getElementById('result')
);
One issue here is that you are breaking a good rule - separate smart and dumb components. https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
The way to do this is to have a parent component that holds all the state and functionality of the children and passes all of this down as props...
//Our smart parent
var SearchContainer = React.createClass({
getInitialState : function() {
return {
value : 'pics'
}
},
handleInput : function(event) {
this.setState({value: event.target.value});
},
render : function() {
return (
<div>
<InputSearch value={this.state.value} onChange={this.handleInput} />
<ButtonSearch value={this.state.value} />
</div>
)
}
});
//Our dumb children
var InputSearch = React.createClass({
propTypes : {
onChange : React.PropTypes.func.isRequired,
value : React.PropTypes.string
},
render : function() {
return (
<input type="text" value={this.props.value} onChange={this.props.onChange} />
)
}
});
var ButtonSearch = React.createClass({
propTypes : {
value : React.PropTypes.string
},
handleClick : function() {
console.log(this.props.value); //log value
},
render : function() {
return (
<button onClick={this.handleClick}>GO! </button>
)
}
});
React.render(<Search />, document.getElementById('result'));
Here we pass the handler function down from parent to child so the input doesn't care what happens to the event it fires on change, it just needs to know that it has a prop called onChange that's a function and it invokes that.
The parent (SearchContainer) handles all of that functionality and passes the changed state down to both the button and the input...
hope that helps
Dan
You left out the event in your handleChange.
handleChange: function(event) {
this.setState({
value: event.target.value
});
},
The main architecture of react is the Parent Child / Master Slave principle.
If you want to pass values between components you have to create relations between.
Like for example
You create your master Component with few default states.
var MyMasterComponent = React.createClass({
getInitialState: function(){
...
},
render: function(){
return(
<ChilComponent1 textiwanttopass={this.state.text} />
);
}
});
With that method you are calling the render of another component within a master component. That way you can pass values from states into another component.
In that case you can access the passed text with this.props.textiwanttopass
I'm new to React and I've been facing a problem since few hours now. Even if I found some topics on Stackoverflow or Google that seems equivalent to my issue, I'm unable to solve it...
I'm using react-select to create a simple form. For now, I have only one multi-select input. I am able to use it as expected but when I press "Submit" I want to retrieve the values selected. I tried with refs, with onChange without success. onChange is never fired, that might be an other issue as well.
var MultiSelect = React.createClass({
onLabelClick: function (data, event) {
console.log(data, event);
},
render: function() {
var ops = []
this.props.categories.forEach(function(category) {
ops.push({ label: category.name, value: category.id });
});
return (
<div>
<Select
name = {this.props.name}
delimiter=" "
multi={true}
allowCreate={true}
placeholder = {this.props.label}
options={ops} />
</div>
);
}
});
var ProductForm = React.createClass({
submit: function () {
console.log("Categories: " + this.state.categories);
},
onCategoryChange: function(e) {
console.log("CATEGORY CHANGED !!!!!!")
this.setState({categories: e.target.value});
},
render: function () {
return (
<form onSubmit={this.submit}>
<MultiSelect label="Choose a Category" name="categories" categories={this.props.categories} onChange={this.onCategoryChange}/>
<button type="submit">Submit</button>
</form>
);
}
});
PS : data categories comes from a Rails controller.
I believe your internal Select component should receive onChange from the props provided to MultiSelect, assuming your intention is to listen to changes on the Select component.
Try something like this inside your MultiSelect's render() method:
return (
<div>
<Select
name = {this.props.name}
delimiter=" "
multi={true}
allowCreate={true}
placeholder = {this.props.label}
options={ops}
onChange={this.props.onChange} />
</div>
);
Side note, I don't think e.target.value is going to work inside onCategoryChange, since react-select doesn't send standard events.
I'm trying to bind a value to a div with react so that I can maintain state for that element (eg. on-off) It looks like I should be using LinkedStateMixin, but my experiment below proves that react doesn't support arbitrary attributes for block level elements. Both elements have default values but the div e.target.value returns undefined from its onclick handler whereas the input element value has been properly set. Any idea how to bind data to the div? Thanks!
var Component = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {message: 'Hello!'};
},
render: function () {
var valueLink = this.linkState('message');
var handleClick = function(e) {
console.log(e.target.value);
valueLink.requestChange(e.target.value);
};
return (
<div>
<input type="text" onClick={handleClick} defaultValue={valueLink.value} />
<div onClick={handleClick} defaultValue={valueLink.value}>
{this.state.message}
</div>
</div>
);
}
});
React.render(<Component />, document.body);
http://jsfiddle.net/su8r5Lob/
var Component = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {
message: 'Hello!',
active: false
};
},
inputClick : function(e) {
console.log(e.target.value);
},
toggleActive : function(e){
console.log('div state', this.state.active);
var newState = !this.state.active;
this.setState({active: newState});
},
render: function () {
var cx = React.addons.classSet;
var valueLink = this.linkState('message');
var classes = cx({
'base-class': true,
'element-active': this.state.active
});
return (
<div>
<input type="text" onClick={this.inputClick} defaultValue={valueLink.value} />
<div onClick={this.toggleActive} className={classes}>
{this.state.message}
</div>
</div>
);
}
});
React.render(<Component />, document.body);
http://jsfiddle.net/su8r5Lob/1/
The reason your code does not work is because <div> elements do not have a value property. Only elements that receive user input have it. So when handleClick is called, valueLink.requestChange receives undefined as a parameter.
I've updated your Fiddle a little bit, and now it does support two-way binding for the onChange event.
var Component = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {message: 'Hello!'};
},
render: function () {
var valueLink = this.linkState('message');
var handleClick = function(e) {
console.log(e.target.value);
valueLink.requestChange(e.target.value);
};
return (
<div>
<input type="text" onChange={handleClick} value={valueLink.value} />
<input type="text" onChange={handleClick} value={valueLink.value} />
</div>
);
}
});
React.render(<Component />, document.body);
But, if you want to bind it to a div element, I give you this suggestion. I'm not sure if it is exactly what you expect, but here it is:
var Component = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {message: 'Hello!'};
},
render: function () {
var valueLink = this.linkState('message');
var handleClick = function(e) {
console.log(e.target.value);
valueLink.requestChange(e.target.value);
};
return (
<div>
<input type="text" onChange={handleClick} value={valueLink.value} />
<div onClick={handleClick.bind(this, {target: {value: 'someDivValue'}})} defaultValue={valueLink.value}>
{this.state.message}
</div>
</div>
);
}
});
React.render(<Component />, document.body);
Note that I gave the div a default value that is going to be set to the valueLink everytime the user clicks it. And I had to change the event on the input to onchange so it can update its value when the user types something.