I have two components, a select list with several options and a button component
What I'd like to do in the UI is that the user can select any option from the select list they want and then press the button to reset the list to 'select'
I'm keeping the parent component as the one source of truth - all updated states are passed back to the parent component, I've actually got this working great in the context of one file with the following code;
class SelectList extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onSelectListChange(e.target.value);
}
render() {
const selectedValue = this.props.selectedValue;
log.debug('SelectListValue(): ', this.props.selectedValue);
return (
<select value={selectedValue} onChange={this.handleChange}>
<option value='One'>One</option>
<option value='select'>select</option>
<option value='Three'>Three</option>
<option value='Four'>Four</option>
<option value='Five'>Five</option>
</select>
);
}
}
class SelectListReset extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onResetChange('select');
}
render() {
return (
<div>
<button onClick={this.handleChange}>Reset list to select</button>
</div>
);
}
}
class Page extends Component {
constructor(props) {
super(props);
this.state={
selectedValue: 'select'
}
this.handleSelectedListChange = this.handleSelectedListChange.bind(this);
this.handleResetChange = this.handleResetChange.bind(this);
}
handleSelectedListChange(selectedValue) {
this.setState({selectedValue});
}
handleResetChange() {
this.setState({selectedValue: 'select'});
}
render() {
log.debug('render(): ', this.props);
log.debug('ParentListValue(): ', this.state.selectedValue);
return (
<div className="content-area">
<div className="container">
<h1>{LANGUAGES_CONTROLLER.format(this.props.languages, 'TitleSettings')}</h1>
<div>
<SelectList
onSelectListChange={this.handleSelectedListChange}
selectedValue={this.state.selectedValue}
/>
<SelectListReset
onResetChange={this.handleResetChange}
selectedValue={this.state.selectedValue}
/>
</div>
</div>
</div>
);
}
But what I've actually like to do is move the reset button to it's own file and this is where I fall over trying to pass the props / state back to the parent.
So the render method would actually look like this
render() {
log.debug('render(): ', this.props);
log.debug('ParentListValue(): ', this.state.selectedValue);
return (
<div className="content-area">
<div className="container">
<h1>{LANGUAGES_CONTROLLER.format(this.props.languages, 'TitleSettings')}</h1>
<div>
<SelectList
onSelectListChange={this.handleSelectedListChange}
selectedValue={this.state.selectedValue}
/>
<TestComponent
onResetChange={this.handleResetChange}
selectedValue={this.state.selectedValue}
/>
</div>
</div>
</div>
);
}
I import TestComponent and then inside of TestComponent is where I will have my code for the SelectListReset component but the problem I'm having is that now the values are sent to it as props which should be immutable right so can't be updated?
That's where my understand stops .. if someone can point me in the right direction on this I'd be very grateful!
Props received from a parent will change if the relevant state in the parent is changed. There's no problem with this and all the re-rendering is handled by React.
You can pass props down as many levels as you like.
Related
I've been at this awhile and I can't get my head around it. I feel so stupid. Can anyone tell me what's wrong?
The console log works currently, and the console.log of the Object states that the state has been updated from false to true.
class ChoiceBar extends React.Component {
constructor() {
super();
this.state = {
handleFirstQuestion: false,
};
this.handleFirstQuestion = this.handleFirstQuestion.bind(this)
}
handleFirstQuestion() {
console.log("Start Rendering First Question")
this.setState({handleFirstQuestion: true}, () => {console.log(this.state);
});
}
render() {
return (
<div>
<center>
<div>
<button onClick={this.handleFirstQuestion.bind(this)}> Start! </button>
<p> </p>
{this.state.handleFirstQuestion
? <FirstQuestionBox />
: null
}
</div>
</center>
</div>
)
}
}
The first thing is that you are binding the function twice, one in constructor and one in onClick event handler.
Second pass props component in constructor and super
constructor(props) {
super(props);
this.state = {
handleFirstQuestion: false,
};
this.handleFirstQuestion = this.handleFirstQuestion.bind(this)
}
return (
<div>
<center>
<div>
<button onClick={this.handleFirstQuestion}> Start! </button>
<p> </p>
{this.state.handleFirstQuestion
? <FirstQuestionBox />
: null
}
</div>
</center>
</div>
)
I don't think you are exporting the class component
write this after the class component
export default ChoiceBar;
you should probably use aero functions and useState hook instead of the class component
for example:
const ChoiceBar = () => {
const [handleFirstQuestion, setHandleFirstQuestion] = useState(false)
}
I am new to React. In fact I am new to any frontend programming lanugage. Therefore I encounter many really weird and sometimes even hilarious problems. I am struggling with sending an array to another compontent. The problem is user creates that array, and it's created dynamically inside render(){return(..)}
class Home extends Component {
constructor(props) {
super(props)
this.chosenItems = [];
}
state = {
items: [],
};
// code to import JSON from backend API, irrelevant, that part works fine
addItem(item){
this.chosenItems.push(item);
console.log(this.chosenItems); //logs created array, everything works like a charm
}
render() {
const {items} = this.state;
return (
//some code
<div key={item.id}>
{item.name} {item.price}<img src = {item.url} className="photo"/><button onClick={() => this.addItem(item)}>ADD</button>
</div>
<Basket dataFromParent = {this.getItems} />
</div>
and Basket class
class Basket extends React.Component {
constructor(props) {
super(props);
this.chosenItems = [];
}
state = {
items: []
};
componentDidUpdate()
{
this.chosenItems = this.props.dataFromParent;
console.log(this.props.dataFromParent);
}
render() {
return (
<div>
<h2>{this.chosenItems}</h2>
<h2>{this.props.dataFromParent}</h2>
</div>
);
}
}
export default Basket;
the problem is console log shows "undefined". Could you tell me what I am doing wrong? Or maybe my entire approach is incorrect and I should look for another solution?
Update
class Home extends Component {
state = {
items: [],
chosenItems []
};
// code to import JSON from backend API, irrelevant, that part works fine
addItem(item){
this.setState(prev => ({
chosenItems: [...prev.chosenItems, item]
}))
}
render() {
const {items, chosenItems} = this.state;
return (
<div>
<div><Basket chosenItems ={this.state.chosenItems} /></div>
<Router>
<div className="container">
<ul>
<Link to="/login">login</Link>
<Link to="/basket">basket</Link>
</ul>
<Route path="/login" component={Login} />
<Route path="/basket" component={Basket} />
</div>
</Router>
<div>
{items.map(item =>
<div key={item.id}>
{item.name} {item.price} {item.quantity} <img src = {item.url} className="photo"/><button onClick={() => this.addItem(item)}>Add!</button>
</div>
)}
</div>
</div>
);
}
}
class Basket extends React.Component {
render() {
return (
<div>
{this.props.chosenItems.map(item =>
<div key={item.id}>
{item.name}{item.price}
</div>
)}
</div>
);
}
}
and that works, but the chosenItems array is printed immediatelty where
<Basket chosenItems ={this.state.chosenItems} />
is located after the button is pressed. And when I click on basket redirection I get
TypeError: Cannot read property 'map' of undefined
Firstly, you must understand that things that you don't set in state don't cause a re-render and hence an updated data isn't reflected on to the UI or passed onto the children.
Secondly, you do not need to store the data passed from parent in child again, you can directly use it from props
class Home extends Component {
state = {
items: [],
chosenItems []
};
// code to import JSON from backend API, irrelevant, that part works fine
addItem(item){
this.setState(prev => ({
chosenItems: [...prev.chosenItems, item]
}))
}
render() {
const {items} = this.state;
return (
<div>
//some code
<div key={item.id}>
{item.name} {item.price}<img src = {item.url} className="photo"/><button onClick={() => this.addItem(item)}>ADD</button>
</div>
<Basket chosenItems ={this.state.chosenItems} />
/div>
)
}
}
class Basket extends React.Component {
render() {
return (
<div>
<h2>{this.props.chosenItems.map(item=> <div>{item.name}</div>)}</h2>
</div>
);
}
}
export default Basket;
I see a couple of problems in the snippet -
You are passing this.getItems to your child component as props. It's never defined in the parent. I think it should have been items array state that you have created.
chosenItems should have been a state and you should dig deeper on how to update a state. There is a setState function, learn abt it.
In child, again the the constructor is written like parent's with chosenItems and items which is not needed. You can use them from props.
Please have a look on https://reactjs.org/docs/react-component.html#setstate how to mutate the state of a component. You will find few more basics over this document.
The reason you are getting undefined in the log is because the this.getItems() in Home component is returning undefined either there is no such method or probably the state variable itself is undefined.
In a nutshell few things:
When you want to pass an array to child component, it is as simple as passing any object or property For eg. (I am hoping you want to pass the choosen items to Basket component)
Always initialise state in constructor.
so chooseItems and items should be a part of state and inside constructor.
Your code should look like:
class Home extends Component {
constructor(props) {
super(props)
this.state = {
chosenItems: [],
items: [],
}
}
addItem(item){
this.setState({
chosenItems: [...this.state.chosenItems, item]
})
console.log(this.chosenItems); //logs created array, everything works like a charm
}
render() {
const {items, chooseItems} = this.state;
return (
items.map(item => {
return (
<div key={item.id}>
{item.name} {item.price}<img src = {item.url} className="photo"/>
<button onClick={() => this.addItem(item)}>ADD</button>
</div>
)
})
<Basket dataFromParent={chooseItems} />
div>
)
}
}
and the Basket component would not need constructor since the required data is coming from parent component:
class Basket extends React.Component {
render() {
return (
<div>
{this.props.dataFromParent.map(item => <h2>{this.props.dataFromParent}</h2>)}
</div>
);
}
}
export default Basket;
I'm trying to pass data from a search component to a result component. The idea is that the input from the search field in the search component will be sent to the result component and used as a parameter for an API-call when the search button is clicked.
I've based the data-flow structure on this article: https://codeburst.io/no-redux-strategy-for-siblings-communication-3db543538959, but I'm new to React and it's a bit confusing.
I tried using the parameter by directly getting it from props like so vinmonopolet.searchProducts({this.props.data}, but I got a syntax error.
I'm also unclear on how one would go about directing onClick events from one component to another.
Parent
class App extends Component {
constructor(){
super();
this.state = { data: '' }
}
fromSearch(param){
this.setState({
data: param
});
}
render() {
return (
<div className="App">
<Navbar />
<Searchbar callback={this.fromSearch.bind(this)} />
<ResultTable data={this.state.data}/>
</div>
);
}
}
Child1
class Searchbar extends React.Component{
getContent(event){
this.props.callback(event.target.value);
}
Searchbar.protoTypes = {
callback: ProtoTypes.func
}
render(){
return(
<div className="search-container">
<div className="search-field">
<input type="text" placeholder="Hva leter du etter?"
onChange={this.getContent.bind(this)}/>
<button type="button" onClick={???}>Search</button>
</div>
...
Child2
class ResultTable extends React.Component{
constructor(){
super();
this.state = {products: []}
}
searchAllProducts(){
const vinmonopolet = require('vinmonopolet')
vinmonopolet.searchProducts({this.props.data}, {sort: ['price', 'asc']}).then(response => {
const data = response.products;
const listItems = data.map((d) =>
<tr key={d.name}>
<td>{d.productType}</td>
<td>{d.name}</td>
<td>{d.price}kr</td>
</tr>
);
this.setState({products: listItems});
})
}
render(){
if(!this.state.products) return <p>Henter data...</p>;
return(
<div className="result-container">
<div className="result-table-header">
<table>
<th>Type</th>
<th>Varenavn</th>
<th>Pris</th>
</table>
</div>
<div className="result-table-body">
<table className="result-table">
{this.state.products}
</table>
</div>
</div>
);
}
}
I'm a React newbie and have a component which is outputting a checkbox list by mapping an array. This is the code that presently works.
export default class First extends React.Component {
constructor(props) {
super(props);
this.state = {
data: data,
};
}
render() {
return (
<div>
{this.state.data.map(d =>
<label key={ d.name } className="control control--checkbox">{d.name}
<input type="checkbox"/>
<div className="control__indicator"></div>
</label>)}
</div>
);
}
}
What I need to do is add an if/else telling the return map function only to render the checkbox list if another variable in the array (called domain) = "HMO". I'm really struggling with the syntax. I think it needs to be inserted below the {this.state.data.map(d => line but am really stuck. Any help would be greatly appreciated.
I believe you're looking for something like this.
export default class First extends React.Component {
constructor(props) {
super(props);
this.state = {
data: data,
};
}
render() {
return (
<div>
{this.state.data.map(d => {
if(d.domain === "HMO"){
return (
<label key={ d.name } className="control control--checkbox">{d.name}
<input type="checkbox"/>
<div className="control__indicator" />
</label>
)}
return null
})}
</div>
)
}
}
The .map function will iterate through each element in your data array, it will then check if that element's domain variable is equal to the string "HMO". If it is, it will return the html that displays the checkbox, otherwise it will return null.
Use Array.filter:
export default class First extends React.Component {
constructor(...args) {
super(...args);
this.state = {
data: data
};
}
getItems() {
return this.state.data
.filter(d.domain === "HMO")
.map(d => (
<label key={ d.name } className="control control--checkbox">{d.name}
<input type="checkbox"/>
<div className="control__indicator"></div>
</label>
));
}
render() {
return (
<div>
{this.getItems()}
</div>
);
}
}
The downside is that you loop twice compared to #MEnf's solution so it can be slower if you have a really long array. The upside is that it looks neater (I know that is quite subjective).
I'm really new with react. I'm trying to get the parent to change page displayed depending on the states. I have a button in my sub-component that should send "true" or "false" to the parent component so it knows if to render it or not. I think it should be done with props like this:
this.state = {
btnNewScreen: this.props.btnNewScreen //true or false
};
But im not getting it to work. Could you give any tips? Here is the full parent - child
parent - maindisplay.js
import React from 'react';
import Mainpage_Addscreen from '../components/subcomponents/mainpage-addscreen';
import Mainpage_Showscreens from '../components/subcomponents/mainpage-showscreens';
//
class MainDisplay extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: false //should be this.props.btnNewScreen?
};
}
render() {
var renderThis;
if (!this.state.btnNewScreen) {
renderThis =
<div>
<Mainpage_Addscreen />
<Mainpage_Showscreens />
</div>
}
else {
//renderThis = <AddScreen />
renderThis =
<div>
<Mainpage_Addscreen />
<h3>Change to this when true (button click)</h3>
</div>
}
return (
<div>
{renderThis}
</div>
);
}
}
export default MainDisplay;
child - mainpage-addscreen.js
import React from 'react';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import Button from 'react-bootstrap/lib/Button';
class Mainpage_Addscreen extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: true
};
this.newScreen = this.newScreen.bind(this);
}
newScreen(e) {
this.setState({ btnNewScreen: !this.state.btnNewScreen });
console.log(this.state.btnNewScreen);
}
render() {
var text = this.state.btnNewScreen ? 'Add new' : 'Screens';
return (
<div className="main_window col-sm-offset-1 col-sm-10">
<h3 id="addscreens">Screens: </h3>
<Button id="addScreen" className="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" onClick={this.newScreen}><Glyphicon id="refresh_screens" glyph="plus" /> {text}</Button>
</div>
);
}
}
export default Mainpage_Addscreen;
What you need to do is to pass a method from the parent to the child, That it can call when the button is clicked. This method that belongs to the parent will change the state.
In MainPage.js
changeButtonState(event) {
this.setState({btnNewScreen: !this.state.btnNewScreen})
}
pass this method to your child component as
<Mainpage_Addscreen buttonClick={this.changeButtonState.bind(this)} />
and finally in the child component,
<Button .... onClick={this.props.buttonClick} />
What you probably need is a callback function, which your parent passes as a prop to your child, and that your child can then call.
Something like this:
// In parent
constructor() {
...
this.onChildClicked = this.onChildClicked.bind(this);
}
onChildClicked() {
this.setState({childWasClicked : True });
}
render() {
...
return (
<div>
<Child onClicked={this.onChildClicked} />
</div>
)
}
// In child
render() {
...
return (
<div>
<button onClick={this.props.onClicked} />
</div>
)
}
PS: I notice that you have a capitalized <Button> component. This is typically for components that you have defined yourself. Standard DOM elements take lowercase, e.g. <div>, <p> etc