I am unable to use something like this.refs.child.state in my application to access state of a child component, hence need an alternative way to do so. Main reason for this is to pass child contents to redux state when a certain button is clicked inside such childs parent component, hence function in parent component needs to pass childs content as one of the parameters.
Depending on the structure of your components (hard to tell when you don't post code), you could fix this just by chaining callbacks via props. I.e.
var Parent = React.createClass({
onChange: function(childValue){
this.setState({childValue: childValue});
},
render: function(){
return <Child onChange={this.onChange} />
}
});
var Child = React.createClass({
handleChange: function(event){
this.props.onChange(event.target.value);
},
render: function(){
return <input onChange={this.handleChange}/>
}
});
Add in as many middle-layers as needed of the form;
var MiddleChildA = React.createClass({
render: function(){
return <MiddleChildB onChange={this.props.onChange} />
}
});
Related
I have component A and B. Component A pass state as prop to component, says it's named show
so in my component B's render function it will be like this
{this.props.show &&
<div>popup content</div>
}
But how I close it now? I have to pass a flag from component B to the parent? as I know it react you can pass stuff back to parent.
In order to pass data from a child to a parent, the parent needs to pass a function capable of handling that data to the child.
var Parent = React.createClass({
getData: function(data){
this.setState({childData: data});
}
render: function(){
return(
<Child sendData={this.getData} />
);
}
});
var Child = React.createClass({
textChange: function(event){
this.setState({textString: event.target.value});
}
buttonClick: function(){
this.props.sendData(this.state.textString);
}
render: function(){
<div>
<input type="text" value={this.state.textString}
onChange={this.textChange}/>
<button onClick={this.buttonClick}
</div>
}
});
There are other ways of handling data, and it might be worth your while creating a data store to store global variables and handle various events. In this way you would keep the data flow of your application one way. In smaller scale cases however, this solution should suffice.
Use the eventBus to send/receive date from child/parent components respectively.
Example below:
class Date extends Component {
constructor(props) {
super(props);
this.state = {
date:'',
}
this.callback = this.callback.bind(this); // register callback method
}
callback(date){ // callback method to receive data
this.setState({date: date});
}
componentDidMount(){
EventBus.on("date", this.callback);
}
render() {
<div>
{this.state.date}
</div>
}
}
From any other component
handleDayClick(day) {
EventBus.publish("date", day);
}
https://github.com/arkency/event-bus
Is it possible in react to do something like this:
var App = React.createClass({
getInitialState: function(){
return {
children: [<div/>, <div/>],
comp: ''
};
},
componentWillMount: function(){
this.setState({
comp: <SomeComponent children={this.state.children}/>
});
},
render: function(){
return (
<div>
{this.state.comp === '' ? this.state.children : this.state.comp}
</div>
);
}
});
When I try to do something similar to this I get: Uncaught TypeError: Cannot read property '_currentElement' of null so I assume the answer is no, but I figure there has to be some way considering
<SomeComponent>
<div/>
</SomeComponet>
where <SomeCompent/> renders a <div/>, is valid. However in this particular case I get the same error doing that, but if you look at something like React-Bootstrap https://react-bootstrap.github.io/, it has to be possible.
Why do you want to pass html tags as state? I'm not saying is bad, but there's always a better solution to what you asking. Let's say a child component passing a state Boolean true or false to parent component( Flux - Action by child component pass to store, parent components can pick up the state with onChange event). With that you could invoke the parent element to render different view.
_onChange: function() {
this.setState(this._getStateFromStores());
},
render: function() {
var view;
if (this.state.childAction) {
view = <SomethingTrue/> ;
}
if (!this.state.childAction) {
view = <SomethingFalse/> ;
}
return (
<div>
{view}
</div>
);
I have two JS files included in page as utility.js and utility1.js Code for utility.js
var HelloWorld = React.createClass({
render: function() {
return (
<p>
Hello, <input type="text" ref="mytestinput" placeholder="Your name here" />!<br />
It is {this.props.date.toTimeString()}
</p>
);
}
});
setInterval(function() {
React.render(
<HelloWorld date={new Date()} />,
document.getElementById('container')
);
}, 1000);
Code for utility1.js
var MyComponent = React.createClass({
handleClick: function() {
// Explicitly focus the text input using the raw DOM API.
React.findDOMNode(HelloWorld.refs.mytestinput).focus();
},
render: function() {
// The ref attribute adds a reference to the component to
// this.refs when the component is mounted.
return (
<div>
<input type="text" ref="myTextInput" />
<input
type="button"
value="Focus the text input"
onClick={this.handleClick}
/>
</div>
);
}
});
React.render(
<MyComponent />,
document.getElementById('container1')
);
The problem here is I want focus on input of HelloWorld Component of utility.js from utility1.js. I saw their is one method as findDOMNode for mounted components. But this code is not working for me. Can Somebody try this JS Fiddle here and let me know possible solution.
You need to create the global event system in order to allow both components communicate with each other if they are not in parent-child relationship. Here is more information about global event system
Here is the solution: jsfiddle
var CustomEvents = (function() {
var _map = {};
return {
subscribe: function(name, cb) {
_map[name] || (_map[name] = []);
_map[name].push(cb);
},
notify: function(name, data) {
if (!_map[name]) {
return;
}
// if you want canceling or anything else, add it in to this cb loop
_map[name].forEach(function(cb) {
cb(data);
});
}
}
})();
var HelloWorld = React.createClass({
componentDidMount: function() {
React.findDomNode(this.refs.mytestinput).focus()
},
...
});
or if your React.js is up-to-date, use this:
componentDidMount() {
this.refs.mytestinput.focus()
}
Refs are local to the component they are defined on, so HelloWorld.refs.mytestinput is not valid. Furthermore, since MyComponent and HelloWorld are part of two different React applications (created by two different calls to React.render), there's no built-in way to access the refs in HelloWorld from MyComponent. You would need to set some kind of global reference to the component, use message passing from one app to the other, emit events of some kind indicating the input should be focused, or use some other method of "global" communication.
Just use
this.refs.myTextInput
https://jsfiddle.net/e0cjqLu2/
I have a table with some data and each element in the table is a React class component. It looks like this:
All i want is to have one checkbox for "check all" feature (top left checkbox). The thing is I don't know how to solve that because of props and state.
I have code like that in single element component:
getInitialState: function() {
return { component: this.props.data };
},
render: function() {
var data = this.state.component;
data = data.set('checked', this.props.data.get('checked'));
...
}
And I know I shouldn't get checked param from props but it is just temporary.
What I have problem with is: When I update checked param in parent it doesn't update state, because getInitialState isn't called after refresh (yep, i know it should be like that).
My question is: can I somehow update state of child component? Or it is better way to achieve that.
With functional components:
An easy way to refresh the children internal state when props provided by parent change is through useEffect():
In the children:
const [data, setData] = useState(props.data);
useEffect( () => {
setData(props.data);
}, [props.data]);
In this way everytime the props.data change the useEffect will be triggered and force to set a new status for some data and therefore the component will "refresh".
My approach is that you should have structure something like this in parent's render:
<ParentView>
{ this.props.rows.map(function(row) {
<ChildRow props={row.props} />
}).bind(this)
}
</ParentView>
And then on row.props you have the information whether current row item is checked or not. When parent checkbox is toggled, you populate all the row.props with the status.
On child, you will receive those with componentWillReceiveProps and you do the magic (e.g. set the correct state) when checkbox is toggled:
componentWillReceiveProps: function(props) {
this.setState({isChecked: props.isChecked});
}
(Info from the React's docs: Calling this.setState() within this function will not trigger an additional render.)
Child element's render would be something like:
<div>
<input type='checkbox' checked={this.state.isChecked} />
<label>{this.props.label}</label>
</div>
You can solve this by storing the checked state of all child elements in the parent only. The children set their checked status based on props only (they don't use state for this) and call a callback supplied by the parent to change this.
E.g., in the child:
render: function() {
//... not showing other components...
<input type="checkbox"
value={this.props.value}
checked={this.props.checked}
onClick={this.props.onClick}>
}
The parent supplies the onClick, which changes the checked status of the child in its state and passes this back to the child when it re-renders.
In the parent:
getInitialState: function() {
return {
allChecked: false,
childrenChecked: new Array(NUM_CHILDREN) // initialise this somewhere (from props?)
}
},
render: function() {
return <div>
<input type="checkbox" checked={this.state.allChecked}>
{children.map(function(child, i) {
return <Child checked={this.state.childrenChecked[i]}
onClick={function(index) {
return function() {
// update this.state.allChecked and this.state.childrenChecked[index]
}.bind(this)
}.bind(this)(i)}
/>
}).bind(this)}
</div>;
}
-- not checked for typos etc.
Please see the react documentation on Lifting State Up.
In your child component, you need to use the props. To update the prop, you need to provide an update function from the parent.
Is there any way passing state from parent component to child component like:
var ParentComponent = React.createClass({
getInitialState: function() {
return {
minPrice: 0
}
},
render: function() {
return (
<div onClick={this.doSomething.bind(this, 5)}></div>
);
}
});
var ChildComponent = React.createClass({
getInitialState: function() {
return {
minPrice: // Get from parent state
}
},
doSomething: function(v) {
this.setState({minPrice: v});
},
render: function() {
return (
<div></div>
);
}
});
I want to change parent state value from child component. In react.js is it possible or not?
There is but it's not intended to work like that in React.
2-way data binding isn't the way to go in React, excerpt from the docs.
In React, data flows one way: from owner to child.
So what you want to do if you want to manipulate parent state in your child component is passing a listener.
//parent component's render function
return (
<Child listenerFromParent={this.doSomething} />
)
//child component's render function
return (
<div onClick={this.props.listenerFromParent}></div>
)
You can use the limelights solution, ie passing a function from the parent to the child.
Or you can also use projects like React-Cursor which permits to easily manipulate state passed from a parent component in a child.
I have made my home made framework (Atom-React, some details here) that also use cursors (inspired by Om), and you can somehow achieve easily 2-way data binding with cursors permitting to manipulate the state managed by a parent component.
Here's an exemple usage:
<input type="text" valueLink={this.linkCursor(this.props.inputTextCursor)}/>
The inputTextCursor is a cursor passed from a parent to a child component, and thus the child can easily change the data of the parent seemlessly.
I don't know if other cursor-based React wrappers use this kind of trick but the linkCursor function is implemented very easily with a simple mixin:
var ReactLink = require("react/lib/ReactLink");
var WithCursorLinkingMixin = {
linkCursor: function(cursor) {
return new ReactLink(
cursor.getOrElse(""),
function setCursorNewValue(value) {
cursor.set(value);
}
);
}
};
exports.WithCursorLinkingMixin = WithCursorLinkingMixin;
So you can easily port this behavior to React-Cursor