I set up an app which has an input box and a title. The title input changes onChange
which updates the title shown. The state is an object with an array {title:[{title: 'Welcome', feature: 'test'}]
, I successfully setState for title, but feature then becomes unknown. See code:
APP.JS
import React from "react";
import Header from "./Header";
export default class Layout extends React.Component {
constructor() {
super();
this.state = {
title: [{
title: 'Welcome',
feature: 'test'
}]
};
}
changeTitle(titleChange) {
this.setState({title: [{title: titleChange }]});
}
render() {
return (
<div>
<Header changeTitle={this.changeTitle.bind(this)} title={this.state.title[0].title} feature={this.state.title[0].feature} />
</div>
);
}
}
HEADER.JS
import React from "react";
import Title from "./Header/Title";
export default class Header extends React.Component {
handleChange(e) {
const title = e.target.value;
console.log(e, title);
this.props.changeTitle(title);
}
render() {
console.log(this.props.title) //This test Works
console.log(this.props.feature) //This test Works
return (
<div>
<Title title={this.props.title} />
<h4> Feature Here: {this.props.feature} </h4> //This disappears after I change input
Title Here: <input value={this.props.title} onChange={this.handleChange.bind(this)} />
</div>
);
}
}
TITLE.JS
import React from "react";
export default class Title extends React.Component {
render() {
return (
<h1>{this.props.title}</h1>
);
}}
So app.js is main, header.js is parent, and title.js is child (If I understand correctly).
After I change, title
because the new title
, but feature
becomes undefined
. Any idea what's wrong?
I might need to use componentWillUpdate
but I'm not fully sure how I would.