I have child components that receive props from a parent, but on an event (button click) in a child I want to setState again with the new props. So the parent passes down all items in a list to the children. In the child prop a button deletes an item in the list. But how can you update the state so the list item is also removed from the view. This is my code:
const Parent = React.createClass({
getInitialState:function(){
return {
items: []
};
},
componentWillMount:function(){
axios.get('/comments')
.then(function(response) {
this.setState({
items: response.data
})
}.bind(this));
},
render() {
return (
<div>
<Child1 data={this.state.items}/>
</div>
);
}
});
export default Parent;
export default function Child1(props){
return(
<div>
{ props.data.map((comment,id) =>(
<p key={id}>
{comment.name}<Delete data={comment.id}/>
</p>
)
)}
</div>
)
}
class Delete extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
Purchase.Action(this.props.data,'remove');
axios.post('/comments', {
item: this.props.data
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return <Button onClick={this.handleClick}>Delete</Button>;
}
}
module.exports = Delete;
So although the comment is deleted at the server, I want to delete the comment from the component view by updating the state.
If you want to delete the comment from the component, you have to update your Parent state.
In order to do that you can create a new method, delete(id), in your Parent component where you remove the deleted item from the state.
const Parent = React.createClass({
getInitialState:function(){
return {
items: []
};
},
componentWillMount:function(){
this.setState({
items: [
{id: 1,name: "Name 1"},
{id: 2,name: "Name 2"},
{id: 3,name: "Name 3"}
]
})
},
delete(id){
// axios.post(...)
let items = this.state.items.filter(item => item.id !== id);
this.setState({items});
},
render() {
return (
<div>
<Child1
data={this.state.items}
handleClick={this.delete} // Pass the method here
/>
</div>
);
}
});
function Child1(props){
return(
<div>
{ props.data.map((comment,id) =>(
<p key={id}>
{comment.name}
<Delete
data={comment.id}
handleClick={() => props.handleClick(comment.id)} // Pass the id here
/>
</p>
)
)}
</div>
)
}
class Delete extends React.Component {
constructor(props) {
super(props);
}
render() {
return <button onClick={this.props.handleClick}>Delete</button>;
}
}
jsfiddle
Related
I'm having trouble updating my state using setState.
I have a parent component where I define my state, as well as a handleClick function which should update the state.
export default class Main extends PureComponent {
state = {
selectedName: '',
selectedTasks: [],
data: [
{
name: 'John',
tasks: ['vacuum', 'cut grass']
},
{
name: 'Jack',
tasks: ['cook breakfast', 'clean patio']
}
]
handleClick = e => {
console.log('Name: ', e.name);
console.log('Tasks', this.state.data.find(el => el.name === e.name).tasks)
const { selectedName, selectedTasks } = this.state;
this.setState({
selectedName: e.name
selectedTasks: this.state.data.find(el => el.name === e.name).tasks
});
console.log('stateAfter', this.state)
};
render() {
const { data } = this.state;
return (
<div>
<Child
data={data}
handleClick={this.handleClick.bind(this)}
/>
</div>
)
}
}
I have a child component that takes the handleClick as props.
export default class Child extends PureComponent {
constructor(props) {
super(props);
}
render() {
console.log('data', this.props.data);
return (
<ResponsiveContainer width="100%" height={500}>
<PieChart height={250}>
<Pie
data={this.props.data}
onClick={this.props.handleClick}
/>
</PieChart>
</ResponsiveContainer>
);
}
}
When I execute the handleClick function the first time, nothing gets updated. But when I execute it the second time, the state does get updated. What am I missing to make state get updated the first time?
this.setState is asynchronous. If you wish to console.log your state after setState then you'll have to do this via the callback.
this.setState({
selectedName: e.name
selectedTasks: this.state.data.find(el => el.name === e.name).tasks
},
() => {
console.log('stateAfter', this.state)
});
I have have code that creates <li> elements. I need to delete elements one by one by clicking. For each element I have Delete button. I understand that I need some function to delete items by id. How to do this function to delete elements in ReactJS?
My code:
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {items: [], text: ''};
}
render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.handleChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}
handleChange(e) {
this.setState({text: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
var newItem = {
text: this.props.w +''+this.props.t,
id: Date.now()
};
this.setState((prevState) => ({
items: prevState.items.concat(newItem),
text: ''
}));
}
delete(id){ // How that function knows id of item that need to delete and how to delete item?
this.setState(this.item.id)
}
}
class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this.delete.bind(this)}>Delete</button></li>
))}
</ul>
);
}
}
You are managing the data in Parent component and rendering the UI in Child component, so to delete item from child component you need to pass a function along with data, call that function from child and pass any unique identifier of list item, inside parent component delete the item using that unique identifier.
Step1: Pass a function from parent component along with data, like this:
<TodoList items={this.state.items} _handleDelete={this.delete.bind(this)}/>
Step2: Define delete function in parent component like this:
delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}
Step3: Call that function from child component using this.props._handleDelete():
class TodoList extends React.Component {
_handleDelete(id){
this.props._handleDelete(id);
}
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this._handleDelete.bind(this, item.id)}>Delete</button></li>
))}
</ul>
);
}
}
Check this working example:
class App extends React.Component{
constructor(){
super();
this.state = {
data: [1,2,3,4,5]
}
this.delete = this.delete.bind(this);
}
delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}
render(){
return(
<Child delete={this.delete} data={this.state.data}/>
);
}
}
class Child extends React.Component{
delete(id){
this.props.delete(id);
}
render(){
return(
<div>
{
this.props.data.map(el=>
<p onClick={this.delete.bind(this, el)}>{el}</p>
)
}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
I have some issue in React that seems to keep last or old state.
I have a parent component called MyLists.js that contain a loop function where I rendered child component called Item.js
{
this.state.listProducts.map(d =>
<Item data={d} />
)}
And in my Item.js component I set state in constructor :
this.state = { showFullDescription: false }
The variable "showFullDescription" allows me to see the entire description of a product. Now I have for example 2 products and all states "showFullDescription" are set to false so :
Product 1 => (showFullDescription = false)
Product 2 => (showFullDescription = false)
Next, I show full description for Product 2 by clicking a button and I set state to true so Product 2 => (showFullDescription = true)
The problem is when I add another product, let's call it "Product 3", the full description of "Product 3" is directly shown and for "Product 2" it is hidden. It seems that last state is reflected on "Product 3".
I am really sorry for my english, it's not my native language
Here is full source code :
MyLists.js
import React, { Component } from 'react';
import ProductService from '../../../../services/ProductService';
import Item from './Item';
class MyLists extends Component {
constructor(props) {
super(props);
this.state = {
products: []
}
this.productService = new ProductService();
this.productService.getAllProducts().then((res) => {
this.setState({
products: res
})
});
}
addProduct(data){
this.productService.addProduct(data).then((res) => {
var arr = this.state.products;
arr.push(res);
this.setState({
products: arr
})
})
}
render() {
return (
<div>
{
this.state.products.map(d =>
<Item data={d} />
)}
</div>
)
}
}
export default MyLists;
Item.js
import React, { Component } from 'react';
import Truncate from 'react-truncate';
class Item extends Component {
constructor(props) {
super(props);
this.state = {
showFullDescription: false
}
}
render() {
return (
<div>
<h2>{this.props.data.title}</h2>
{
!this.state.showFullDescription &&
<Truncate lines={10} ellipsis={<a className="btn btn-primary read-more-btn" onClick={() => this.setState({showFullDescription: true})}>Show More</a>}>
{this.props.data.description}
</Truncate>
)}
{
this.state.showFullDescription &&
<span>
{this.props.data.description}
</span>
}
</div>
)
}
}
export default Item;
You have some syntax problems and missing && for !this.state.showFullDescription.
I've slightly changed the component and use ternary operator to render conditionally. It is a little bit ugly right now, the logic can be written outside of the render. Also, I suggest you to use a linter if you are not using.
MyLists.js
class MyLists extends React.Component {
state = {
products: [
{ id: 1, description: "Foooooooooooooooooooooooooooooooooooooooooo", title: "first" },
{ id: 2, description: "Baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrr", title: "second" },
{ id: 3, description: "Baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz", title: "third" },
]
}
render() {
return (
<div>
{
this.state.products.map(d =>
<Item data={d} />
)}
</div>
)
}
}
Item.js
class Item extends React.Component {
state = {
showFullDescription: false,
}
render() {
return (
<div>
<h2>{this.props.data.title}</h2>
{ !this.state.showFullDescription
?
<Truncate lines={3} ellipsis={<span>... <button onClick={() => this.setState({showFullDescription: true})}>Read More</button></span>}>
{this.props.data.description}
</Truncate>
:
<span>
{this.props.data.description}
</span>
}
</div>
)
}
}
Here is working sandbox: https://codesandbox.io/s/x24r7k3r9p
You should try mapping in the second component as:
class Item extends React.Component {
state = {
showFullDescription: false,
}
render() {
return (
<div>
{this.props..data.map(data=>
<h2>{this.props.data.title}</h2>
{ !this.state.showFullDescription
?
<Truncate lines={3} ellipsis={<span>... <button onClick={() =>
this.setState({showFullDescription: true})}>Read More</button>
</span>}>
{this.props.data.description}
</Truncate>
:
<span>
{this.props.data.description}
</span>)}
}
</div>
)
}
}
You should have a 'key' property (with unique value) in 'Item' - No warnings about it in console?
I have a button for each div. And when I press on it, it has to show the div with the same key, and hide the others.
What is the best way to do it ? This is my code
class Main extends Component {
constructor(props) {
super(props);
this.state = {
messages: [
{ message: "message1", key: "1" },
{ message: "message2", key: "2" }
]
};
}
handleClick(message) {
//something to show the specific component and hide the others
}
render() {
let messageNodes = this.state.messages.map(message => {
return (
<Button key={message.key} onClick={e => this.handleClick(message)}>
{message.message}
</Button>
)
});
let messageNodes2 = this.state.messages.map(message => {
return <div key={message.key}>
<p>{message.message}</p>
</div>
});
return <div>
<div>{messageNodes}</div>
<div>{messageNodes2}</div>
</div>
}
}
import React from "react";
import { render } from "react-dom";
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [
{ message: "message1", id: "1" },
{ message: "message2", id: "2" }
],
openedMessage: false
};
}
handleClick(id) {
const currentmessage = this.state.messages.filter(item => item.id === id);
this.setState({ openedMessage: currentmessage });
}
render() {
let messageNodes = this.state.messages.map(message => {
return (
<button key={message.id} onClick={e => this.handleClick(message.id)}>
{message.message}
</button>
);
});
let messageNodes2 = this.state.messages.map(message => {
return (
<div key={message.key}>
<p>{message.message}</p>
</div>
);
});
const { openedMessage } = this.state;
console.log(openedMessage);
return (
<div>
{openedMessage ? (
<div>
{openedMessage.map(item => (
<div>
{" "}
{item.id} {item.message}{" "}
</div>
))}
</div>
) : (
<div> Not Opened</div>
)}
{!openedMessage && messageNodes}
</div>
);
}
}
render(<Main />, document.getElementById("root"));
The main concept here is this following line of code.
handleClick(id) {
const currentmessage = this.state.messages.filter(item => item.id === id);
this.setState({ openedMessage: currentmessage });
}`
When we map our messageNodes we pass down the messages id. When a message is clicked the id of that message is passed to the handleClick and we filter all the messages that do not contain the id of the clicked message. Then if there is an openedMessage in state we render the message, but at the same time we stop rendering the message nodes, with this logic {!openedMessage && messageNodes}
Something like this. You should keep in state only message key of visible component and in render method you should render only visible component based on the key preserved in state. Since you have array of message objects in state, use it to render only button that matches the key.
class Main extends Component {
constructor(props) {
super(props);
this.state = {
//My array messages: [],
visibleComponentKey: '',
showAll: true
};
handleClick(message) {
//something to show the specific component and hide the others
// preserve in state visible component
this.setState({visibleComponentKey : message.key, showAll: false});
};
render() {
const {visibleComponentKey, showAll} = this.state;
return (
<div>
{!! visibleComponentKey && ! showAll &&
this.state.messages.filter(message => {
return message.key == visibleComponentKey ? <Button onClick={e => this.handleClick(message)}>{message.message}</Button>
) : <div /> })
}
{ !! showAll &&
this.state.messages.map(message => <Button key={message.key} onClick={e => this.handleClick(message)}>{message.message}</Button>)
}
</div>
);
}
}
I haven't tried it but it gives you a basic idea.
I cannot reply to #Omar directly but let me tell you, this is the best code explanation for what i was looking for! Thank you!
Also, to close, I added a handleClose function that set the state back to false. Worked like a charm!
onCloseItem =(event) => {
event.preventDefault();
this.setState({
openedItem: false
});
}
I would like to use AddItem to add items to a list in another component. However, I keep getting undefined.
How do I correctly add an item to a list?
I've put it inside a CodeSandbox too: https://codesandbox.io/s/Mjjrm3zrO
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: [x.movies],
};
}
render() {
return (
<div>
<CreateNew addItem={item => this.setState({ movie: [item].concat(this.state.movie) })} />
{x.movies.map(movie => (
<Result key={movie.id} result={movie} addItem={item => this.setState({ genres: [item].concat(this.state.genres) })} />
))}
</div>
);
}
}
class CreateNew extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
genres: '',
};
}
handleSubmit1 = (e, value) => {
e.preventDefault();
this.props.addItem(this.state.value)
console.log(this.props.item);
};
onChange = e => {
this.setState({ value: {'name': e.target.value}, genres: [{ name: 'Test', type: 1 }, { name: 'Foo', type: 10 }] });
console.log(this.state.value);
};
render() {
const { value, genres } = this.props;
return (
<form onSubmit={this.handleSubmit1}>
Add a new movie
<input onChange={this.onChange} type="text" />
<button type="submit">Save</button>
</form>
);
}
}
class Result extends React.Component {
render() {
const { result } = this.props;
return (
<div>
<li>
{result.name} {' '}
({result.genres.map(x => x.name).join(', ')}){' '}
</li>
</div>
);
}
}
Changes:
1. Instead of sending only name from child component send the whole state variable that will contain name and genres.
handleSubmit1 = (e, value) => {
e.preventDefault();
this.props.addItem(this.state)
};
2. You are storing the initial value movies from json to state variable so use that state variable to create the ui, because you are updating the state variable once you adding any new item, so if you use initial json to create ui then new item will not reflect in ui.
{this.state.movies.map(movie => (
<Result key={movie.id} result={movie} />
))}
3. Update the state variable movies like this:
<CreateNew addItem={item => this.setState({ movies: [{name: item.value.name, genres: item.genres}].concat(this.state.movies) })} />
Check the working solution: https://codesandbox.io/s/3nD0RgRp