score:2
class EntriesTable extends React.Component {
constructor(props) {
super(props);
console.log(this.props.plannerId);
this.state = {
editableTasks: [],
tasks: [],
plannerId: this.props.plannerId,
};
var state = this.state;
/* This isn't completely necessary but usually it is recommended you
* bind the class method in the constructor so it isn't bound on each
* render
*/
this.EditTask = this.EditTask.bind(this);
}
componentDidMount() {
this.getTasks(this.state.plannerId);
}
EditTask(id) {
/* So jQuery and react are kind of at odds with each other on fundamentals
* React is supposed to be declarative whereas jQuery is imperative. Using
* jQuery and React together is typically discouraged unless there is a real
* need for it. In React you are supposed to define how you want the UI to render
* based on some variables. You have two options available to you props and state.
* props are passed from the parent and are immutable. state is managed within that
* component and is mutable. So we have added a variable called editableTasks to your
* state that will contain an array of all editable tasks. Instead of trying to hide
* or show items here, we are simply going to add the id of now editable task to that
* array
*
*/
var nextState = this.state;
nextState.editableTasks.push(id);
this.setState(nextState);
}
updateTask(id, name) {
$.ajax({
type: "GET",
url: "/Task/Update",
data: { id: id, name: name },
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
//this.setState({ tasks: data.ReturnObject, loading: false });
}.bind(this),
error: function (xhr, status, err) {
console.log(err);
}
});
}
createTask(name) {
//make api call to create planner here.
var data = {
Name: name,
PlannerId: model.plannerId,
Status: "Not Complete",
Description: "",
Affiliation: "",
Footprint: "",
Created: new Date(),
Modified: null,
};
$.ajax({
type: "POST",
url: "/Task/Add",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
this.getTasks(model.plannerId);
}.bind(this),
error: function (xhr, status, err) {
console.log(err);
}
});
}
getTasks(id) {
this.setState({ tasks: [], loading: true });
$.ajax({
type: "GET",
url: "/Task/GetAll",
data: { id: id },
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
this.setState({ tasks: data.ReturnObject, loading: false });
}.bind(this),
error: function (xhr, status, err) {
console.log(err);
}
});
}
render() {
const tasks = this.state.tasks.map((task) => {
var editable = this.state.editableTasks.filter(id => id === task.Id).length > 0;
/* Now here we are going to check whether this item is editable
* based on id. So we assign a variable that will eval to a bool
* based on whether when you filter editableTasks to see if it contains
* the current items id the length is greater than 0.
*
* Now below instead of applying some id attribute we are going to return either
* the input or the span based on whether it is editable using a ternary operation
*
*/
return (
<li key={task.Id} className="list-group-item" style={{minHeight: '50px'}}>
<div className="pull-left" style={{width: '50%'}}>
{editable ? <input type="text" /> : <span onClick={this.EditTask( task.Id)}>{task.Name}</span>}
</div>
<div className="pull-right" style={{marginTop: '-5px', width: '50%'}}>
<div className="pull-right">
<button className="btn btn-default">Add</button>
<button className="btn btn-default">Edit</button>
</div>
</div>
</li>
);
});
return (
<div className="table-wrapper">
<div className="task-container">
<h3>{this.props.rowName}</h3>
</div>
<ul id="tasksContainer">
{tasks}
<li className="list-group-item list-group-item-last"><input type="button" value="Add Task" onClick={this.addTask.bind(this)} className="btn btn-success btn-override" /></li>
</ul>
</div>
);
}
};
So the above should work for making items editable. Now it doesn't handle actually editing them or returning them to non-editable state. But this should illustrate how you should be accomplishing this the 'react-way'.
I encourage you to drop jQuery. jQuery is going to make your React code harder to manage and make it harder to embrace the react way. If you need something for ajax requests, there are plenty of smaller libraries that just as well suited (superagent is highly recommended but a quick google can lead you to many other)
Let me know if you have any other question.
score:1
To show dynamically show/hide a list of items in react implement Visible.js in your file:
import React, { Component } from 'react'
import { Link, Router } from 'react-router';
import { connect } from 'react-redux';
import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import '../../../static/images/cms-img3.jpg';
import '../../../static/images/cms-img4.jpg';
import '../../../static/images/cms-img5.jpg';
import '../../../static/images/grid-list/vegetables-790022_640.jpg';
import '../../../static/images/grid-list/00-52-29-429_640.jpg';
import '../../../static/images/grid-list/burger-827309_640.jpg';
import '../../../static/images/grid-list/camera-813814_640.jpg';
import '../../../static/images/grid-list/morning-819362_640.jpg';
import '../../../static/images/grid-list/hats-829509_640.jpg';
import '../../../static/images/grid-list/honey-823614_640.jpg';
import '../../../static/images/grid-list/water-plant-821293_640.jpg';
import '../../../static/images/video.mp4';
import '../../../static/images/video123.mp4';
class VisibleData extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
this.onTodoClick = this.onTodoClick.bind(this);
}
componentDidMount() {
fetch('http://new.anasource.com/team9/news-api/?operation=view')
.then(result => result.json()
.then(news => {
this.setState({ items: news.news });
})
);
}
componentWillMount() {
window.onpopstate = (event) => {
this.componentDidMount();
};
}
onTodoClick(id) {
this.setState({
items: this.state.items.filter(item => item.news_id == id)
});
}
render() {
return (
<Data show={this.onTodoClick} items={this.state.items} />
)
}
}
class Data extends Component {
onTodoClick(e, id) {
this.props.show(id);
}
render() {
return (
<div>
{this.props.items.map(item => {
const p = item.news_type == "image";
const r = item.news_type == "video";
return <Link to={"todo/#/" + item.news_id} key={item.news_id}>
<Card onClick={(e) => this.onTodoClick(e, item.news_id)} style={{margin:15}}>
<CardTitle title={item.news_title} subtitle={item.news_description}>
<CardMedia>
{p
? <img src={item.news_src_url} />
: null
}
</CardMedia>
<CardMedia>
{r
? <video controls><source src={item.news_src_url} type="video/mp4"/></video>
: null
}
</CardMedia>
<div className='date'>{item.news_created_date}</div>
</CardTitle>
</Card>
</Link>
})
}
</div>
)
}
}
export default VisibleData;
Source: stackoverflow.com
Related Query
- How to dynamically show/hide a list of items in react
- How to conditionally show list items in React based on screen size
- How to show and hide some columns on React Table?
- how to hide and show a div in react
- How to dynamically show hide Formik form field depending on another form field
- how to hide or show a div if checkbox is selected in React JS
- How to add components to list dynamically in React with no redundant render?
- how to hide and show loading spinner - Activity Indicator react native, managing props and state
- How to have different style for items at certain locations in a list in React Native?
- React - how to use hooks to hide or show a component based on an onChange event
- React show same list of items when browser back button is clicked
- how to create a space between list items in React material
- How can show and hide react components using hooks
- How to dynamically show or hide form fields depending on the state of a BooleanInput field in react-admin?
- How do I apply CSS transitions (e.g. fade-ins) to a list of items in React so their animations are sequenced one after the other on render?
- React JS - How can I show / hide some parts of component based on URL path?
- How to deselect list items in react admin custom bulk action buttons
- how to show and hide popup only when promise is active ? React
- React table how to show 3 items each row using map loop
- How to hide and show list contents: ReactJS
- How to dynamically show loader on react button
- React MaterialTable editable row validation - how to show and hide error?
- How to show message when filtered list is empty in React
- How to hide a column on REACT Material table in all rows and show it on Edit for the Particular Row I am editing and Add Operations on new row adding?
- How to Hide and show HTML based on a cookie existing or not in a React App
- How can I render list items dynamically and recursively from a nested array?
- How to show and hide components in React to implement a multiple steps form?
- I want to show and hide a form on toggle of a radio button in React js . Im trying how to use react hooks to hide or show a component on onChange even
- how to set ref in list of items react js?
- How to reduce render time while rendering huge list of items in Ionic React
More Query from same tag
- Unable to change default value for react-select field
- How to change borderRight color of Material UI drawer?
- How to change react styling dependent on condition
- Custom modal background diming in react
- ListItem as a submit button
- Array not resetting after changing query text
- React Hook "useDispatch" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
- Fetch data using an id from an api but display an alternative text to address bar e.g. content_title in Next.js
- props undefined (component update)
- React-Router V4 - Passing Props to Render function in Route Component to generate new component
- How to make the first option unselected while the component is rendered in select with multiple?
- Property 'value' does not exist on 'EventTarget' in TypeScript
- React controlled contenteditable
- how to update inner array of objects in react use state
- Why is TinyMCE displaying HTML tags?
- Can I Fastclick ReactJS running in Cordova
- How to print substring in React JSX?
- package.json not found when moving from Dockerfile to docker-compose
- react javascript arrow function without arrows?
- Smooth animation when turning off a conditionally rendered component in React
- How to append multiple values in setstate for array object Reactjs
- Functional components, reactJS. I have a button next to a span inside a div. I want the button to target the span so I can delete the span on click
- Using react-hook-form's ref is throwing errors in the console if I use a custom component instead of normal HTML5 input tag
- React Router Dom child routes
- React access props from inside a javascript event listener
- Why I'm getting - Rendered more hooks than during the previous render
- How can I use react-hooks in a reactjs library dev environment?
- setState of dynamic multidimensional object
- React: useState filter array not updating state
- assert that only single child is passed in `this.props.children`