Ehssan Ehssan - 3 months ago 12
React JSX Question

How to achieve MVVM like frameworks in Reactjs

I have a simple problem. I think, I misunderstand the ReactJS usage.

I want to author some low level reusable components to build my forms in a standard layout.

Consider something like this.

var Note = React.createClass({

getInitialState: function() {
return ActionData.Model; //the form model
},

render: function () {
var model = this.state;
return (
<Fieldset id="testId" Legend={Language.Note}>
<SingleColumn Lable="Note">
<Textarea value={model.Text} />
</SingleColumn>
<TwinColumn RightLable="Date" LeftLable="">
<DatePicker ReadOnly="true" Date={model.DisplayDate} />
<Checkbox Title="show " />
</TwinColumn>
<input type="button" value="Save" onClick={this.save} />
</Fieldset>
)
},

save: function () {
var model = this.state;
//save the model here ... .
}
});

$(function () {
ReactDOM.render(<Note />, $("#myContent")[0]);
})


And for instance in 'Textarea' component

var Textarea = React.createClass({

getInitialState: function() {
return {
value: this.props.value
};
},

render: function () {
return <input type="text" className="form-control" value={this.state.value} onChange={e => this.setState({value: e.target.value})} />
}
});


How can I update the 'Note' component state on 'Textarea' change state? (performing something like MVVM frameworks).

Am I walking in the correct direction?!

Is ReactJs capable of doing such things !?

Answer

You should pass a function from your Note component to the Textarea component via props:

<Textarea value={model.Text} onValueChange={(value) => this.setState({ value })} />

In this way your child component Textarea simply can simply call the passed onValueChange function:

return (
  <input type="text" className="form-control"
  value={this.state.value} 
  onChange={e => this.props.onValueChange(e.target.value)} />
);