Ivo Ivo - 1 year ago 68
React JSX Question

React/Meteor - this.state from props gets undefined

I need to pass props to my initial state for an edit form (as I want then the value of the form to be equal to the state) but I can't seem to have it working. The component doesn't give the props to the initialState as it firsts load with an empty props, I think due to the createContainer. I tried lot of things (componentDidMount, WillMount, WillReceiveProps...) but didn't succeed to have it work. The code is below, any idea to help ?

import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import moment from 'moment';
import { createContainer } from 'meteor/react-meteor-data';

import { Blogposts } from './../api/blogposts';

export class BlogpostEditItem extends React.Component {

constructor(props){
super(props);
this.state = {
title: this.props.blogpost.title,
body: this.props.blogpost.body
}
}

handleBodyChange(e) {
const body = e.target.value;
this.setState({ body });
}

handleTitleChange(e) {
const title = e.target.value;
this.setState({ title });
}

onSubmit(e) {
e.preventDefault();
this.props.call('blogposts.update', this.props.blogpost._id, this.state.title, this.state.body,);
}

renderEditForm() {
return(
<div>
<input onChange={this.handleTitleChange.bind(this)} value={this.state.title} placeholder="Title" type="text"/>
<textarea onChange={this.handleBodyChange.bind(this)} value={this.state.body} placeholder="Body"></textarea>
<button onClick={this.onSubmit.bind(this)}>Submit Blogpost</button>
</div>
)
}

render() {
return (
<div>
{ this.props.blogpost ? this.renderEditForm() : 'Pas de post' }
</div>
);
}
}

export default createContainer(({params}) => {
Meteor.subscribe('blogposts');

return {
blogpost: Blogposts.findOne(params.id),
call: Meteor.call
}
}, BlogpostEditItem)


I also tried to pass the props as defaultValue and keep the state as value but it doesn't allow to have both on a form. Any idea how I could solve my issue ?
Thanks in advance.

Answer Source

You can access component props through props not this.props

constructor(props){
    super(props);
    this.state = {
        title: props.blogpost.title,
        body: props.blogpost.body
    }
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download