How could I edit a users from this API in local state? - javascript

I need to have an edit button to edit the users first name, last name from the api but only update the input in local state. I've done a lot of research but can't find exactly what I'm looking for. I'm trying not to bring in other libraries (other than lodash possibly?). I've found a lot of other examples but its bringing in other libraries. Any suggestions would help (even on the code I have currently to help clean it up a bit.)
import React, { Component } from "react";
import axios from "axios";
import User from './User'
class App extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
searchTerm: '',
alphabetical: 'az'
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
axios.get("https://randomuser.me/api/?results=20")
.then(response => {
console.log(response.data.results);
this.setState({ users: response.data.results });
})
.catch(error => {
console.log(error);
});
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
let sortedUsers;
if (this.state.alphabetical === "az") {
console.log("sorted");
sortedUsers = this.state.users.sort((a, b) =>
a.name.first > b.name.first ? 1 : -1
);
}
let filteredUsers = sortedUsers;
if (this.state.searchTerm)
filteredUsers = this.state.users.filter(u =>
u.name.first.startsWith(this.state.searchTerm) || u.name.last.startsWith(this.state.searchTerm)
);
const userNames = filteredUsers.map(u => {
return <User
key={u.email}
name={u.name.first}
last={u.name.last}
image={u.picture.medium}
email={u.email}
city={u.location.city}
state={u.location.state}
cell={u.cell}
/>;
});
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Search for user:
<input
type="text"
name="searchTerm"
value={this.state.searchTerm}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
<select
name="alphabetical"
value={this.state.alphabetical}
onChange={this.handleChange}>
<option selected value="az">
A to Z
</option>
<option value="za">Z to A</option>
</select>
{userNames}
</div>
);
}
}
export default App

Related

How to Enter Text By User Input in React JS

I am trying to get the user to input data for my TODO App instead of picking up data from a predefined array.
Below is my Parent component
import React from "react"
import TodoItem from "./TodoItem"
import todosData from "./todosData"
class App extends React.Component {
constructor() {
super()
this.state = {
name: "",
todos: todosData
}
this.handleChange = this.handleChange.bind(this)
this.nameEnter = this.nameEnter.bind(this)
}
handleChange(id) {
this.setState(prevState => {
const updatedTodos = prevState.todos.map(item => {
if (item.id === id){
return {
...item,
completed: !item.completed
}
}
return item
})
return {
todos: updatedTodos
}
})
}
nameEnter(){
var name = this.name
console.log(name)
}
render() {
const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item}
handleChange = {this.handleChange} nameEnter= {this.nameEnter}/>)
return (
<div className="todo-list">
{todoItems}
</div>
)
}
}
export default App
This one is the child component where I have added input fields
import React from "react"
function TodoItem(props) {
return (
<div className="todo-item">
<input
type = "checkbox"
checked = {props.item.completed}
onChange = { () => props.handleChange(props.item.id) }
/>
<input type = "text" name= "name" />
<p>{props.item.text}</p>
</div>
)
}
export default TodoItem
This is how my page looks. Instead of predefined text example:"GROCERRY SHOPPING", I want the user to enter text and it should be in place of that.
Ok so here it is
<input onChange={(e)=>handleChange(e)}/>
//react hooks
const [values,setValues] = useState({inputValue: 'predefined'});
handleChange = (e)=>{
setValues({...values,[e.target.name]: e.target.value})
}
//classes
handleChange = (e)=>{
this.setState({[e.target.name]:e.target.value});
}
this generic and can apply to a number of inputs, not just one
import React from "react"
class Form extends React.Component {
constructor() {
super()
this.state = {
name: ""
}
}
onChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
const {name} = this.state
return (
<input type="text" name="name" value={name} onChange={this.onChange}/>
)
}
}
export default Form
changeInputVal (ev, index) {
ev.persist();
const newArr = this.state.inputArrVal;
newArr[index]=ev.target.value;
this.setState({inputArrVal:newArr, currentPage:1});
}
you need to do something like that in TodoItem --
where --
1- inputArrVal:{} is object And
2- "this.changeInputVal(event, props.item.id)}/>"

Trouble with Axios post request in basic MERN stack app

I want to create an axios post request that sends the id's of a bull and a heifer chosen by a user to my server to calculate traits (in this case milk production) for their offspring. I'm trying to trigger it after the submit button is clicked. I think I'm not sending the id's as properly formatted params for the server to process.
import React, { Component} from 'react';
import axios from 'axios';
class Dropdown extends Component {
constructor (props) {
super(props)
this.handleInputChange = this.handleInputChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
bullId: '',
heiferId: ''
}
}
//this updates state with new bull & heifer
handleInputChange(event) {
const target = event.target;
const value = target.value;
target.clicked = target.value;
const name = target.name;
console.log(target.name)
;
this.setState({
[name]: value
});
console.log(this.state);
}
handleChange = (event) => {
var bull = event.target.value
var heifer = event.target.value
console.log(heifer)
console.log(bull)
};
onSubmit(e) {
e.preventDefault();
const pairing = {
heifer: this.state.heiferId,
bull: this.state.bullId
}
console.log(pairing)
axios.post('http://localhost:8000/traits/:bullId/:heiferId', pairing)
.then(res => console.log(res.data));
this.setState({
bullId:"",
heiferId:""
})
}
render() {
return (
<div>
<form>
<label>Bulls
<select
name={"bullId"}
value ={this.state.bullId}
onChange= {this.handleInputChange}>
<option value="5defc2b5b9283d6de054e0f0">Buddy</option>
<option value="5defc2b5b9283d6de054e0f1">Cooper</option>
<option value="5defc2b5b9283d6de054e0f2">Maxwell</option>
<option value="5defc2b5b9283d6de054e0f3">Gus</option>
<option value="5defc2b5b9283d6de054e0f4">Paul</option>
<option value="5defc2b5b9283d6de054e0f5">Phil</option>
</select>
</label>
<br />
<label>Heifers
<select
name={"heiferId"}
value={this.state.heiferId}
onChange= {this.handleInputChange}>
<option value="5defc49cb9283d6de054e0f6">Sally</option>
<option value="5defc49cb9283d6de054e0f7">Patches</option>
<option value="5defc49cb9283d6de054e0f8">Maxine</option>
<option value="5defc49cb9283d6de054e0f9">Peach</option>
<option value="5defc49cb9283d6de054e0fa">Paula</option>
<option value="5defc49cb9283d6de054e0fb">Flower</option>
</select>
</label>
</form>
<button onClick={this.onSubmit}>submit</button>
</div>
)}
}
export default Dropdown;
Heifer.findOne({_id: req.params.heiferId}).then(function(heifer){
Bull.findOne({_id: req.params.bullId}).then(function(bull){
console.log(bull);
console.log(heifer);
let heiferMilkProduction = heifer.milkProduction;
let bullMilkProduction = bull.milkProduction;
if (heiferMilkProduction > bullMilkProduction) {
heiferMilkProduction += heiferMilkProduction * .1
bullMilkProduction -= bullMilkProduction * .1
} else {
bullMilkProduction += bullMilkProduction * .1
heiferMilkProduction -= heiferMilkProduction * .1
};
const calfTraits = {
bullMilkProduction,
heiferMilkProduction
}
res.send(calfTraits);
})
})
});```
You want something like
axios.post(`http://localhost:8000/traits/${this.state.bullId}/${this.state.heiferId}`)
The :bullId syntax in a string does nothing in react, you have to build the string like any other regular string. Its used in express for the routes as a template.
You need to embedded the value of 'bullId' and 'heiferId' in your url you are using to fetch data instead of the string.
onSubmit(e) {
e.preventDefault();
const { bullId, heiferId } = this.state;
axios.post(`http://localhost:8000/traits/${bullId}/${heiferId}`, {})
.then(res => console.log(res.data));
this.setState({
bullId:"",
heiferId:""
})
}

using component state in another component react js

Im working on a little web app, and im stuck on getting the answers data from answer class that i created.
to sum the project, i have a class createQuiz, where i handle the input for question data, and i have an answerOptions state array to collect all the answers, but i created another component answer to have the states of the answers and when i modify them, the answeroptions dont update.
Here is the code for the answer class :
import React, {Component} from 'react';
import createQuiz from './CreateQuiz'
export default class Answer extends Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
this.ChangeValidityState = this.ChangeValidityState.bind(this);
this.state = {
answerText : '',
answerValidity : false
}
}
getCurrentState(){
return (this.state)
}
handleInputChange(event) {
this.setState({
answerText : event.target.value
})
}
onChangeAnswerValidity(event){
this.setState({
answerValidity : !event.target.value
})
}
ChangeValidityState(event){
this.setState({
answerValidity : !event.target.value
})
}
render() {
return (
<div>
<input type="text"
className="form-control"
value={this.state.answerText}
onChange={this.handleInputChange}
/>
<input type="radio"
className="form-control"
value={this.state.answerValidity}
checked={this.state.answerValidity}
onChange={this.onChangeAnswerValidity}
/>
</div>
)
}
}
and here is the code for the create quiz class :
import React, {Component} from 'react';
import axios from 'axios';
import Answer from './Answer';
export default class CreateQuiz extends Component {
constructor(props) {
super(props);
this.onChangeQuestion = this.onChangeQuestion.bind(this);
this.onChangeQuestionTitle = this.onChangeQuestionTitle.bind(this);
this.onChangeAnswerOptions = this.onChangeAnswerOptions.bind(this);
this.onAddItem = this.onAddItem.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.onChangeQuestionAutor = this.onChangeQuestionAutor.bind(this);
this.onChangeValue = this.onChangeValue.bind(this);
this.onChangeAnswerValidity = this.onChangeAnswerValidity.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// this.GenerateAnswers = this.GenerateAnswers.bind(this);
this.state = {
questionTitle: '',
questionAutor: '',
question: '',
answers : [],
answerOptions: [],
}
}
onChangeValue = event => {
this.setState({ currentAnswerValue: event.target.value });
};
onAddItem = () => {
// not allowed AND not working
this.setState(state => {
const newAnswer = {
answerText : '',
answerValidity : false
};
const list = this.state.answerOptions.push(newAnswer);
return {
list,
};
});
};
handleInputChange(event) {
const newIds = this.state.answerOptions.slice() //copy the array
const index = this.state.answerOptions.findIndex((el) => (el.id === event.params.id))
newIds[index].answerText = event.target.value //execute the manipulations
this.setState({answerOptions: newIds}) //set the new state
}
onChangeAnswerValidity(event){
const newIds = this.state.answerOptions.slice() //copy the array
const index = this.state.answerOptions.findIndex((el) => el.answerText === event.target.value)
newIds[index].answerValidity = event.target.value //execute the manipulations
this.setState({answerOptions: newIds}) //set the new state
}
onChangeQuestionAutor(e){
this.setState({
questionAutor: e.target.value
});
}
onChangeQuestionTitle(e) {
this.setState({
questionTitle: e.target.value
});
}
onChangeQuestion(e) {
this.setState({
question: e.target.value
});
}
onChangeAnswerOptions(e) {
this.setState({
answerOptions: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
console.log(`Form submitted:`);
console.log(`questionTitle: ${this.state.questionTitle}`);
console.log(`questionAutor: ${this.state.questionAutor}`);
console.log(`question: ${this.state.question}`);
// this.GenerateAnswers();
console.log(`answerOptions: ${this.state.answers}`);
const newQuiz = {
questionTitle: this.state.questionTitle,
questionAutor: this.state.questionAutor,
question: this.state.question,
answerOptions: this.state.answers,
}
axios.post('http://localhost:4000/quizzes/add', newQuiz)
.then(res => console.log(res.data));
this.setState({
questionTitle: '',
questionAutor: '',
question: '',
answers : [],
answerOptions: []
})
}
answerList(){
return this.state.answerOptions.map(function(currentAnswer, index) {
return <Answer answer = {currentAnswer} key = {index}/>;
});
}
// GenerateAnswers(){
// const newAnswers = this.state.answers
// this.state.answerOptions.map(function(currentAnswer, index){
// const newAnswer = this.state.answerOptions[index].getCurrentState()
// newAnswers.push(newAnswer)
// });
// this.setState({answers: newAnswers});
// }
render() {
return (
<div style={{marginTop: 20}}>
<h3>Create new question</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Question Title: </label>
<input type="text"
className="form-control"
value={this.state.questionTitle}
onChange={this.onChangeQuestionTitle}
/>
</div>
<div className="form-group">
<label>Question Autor: </label>
<input type="text"
className="form-control"
value={this.state.questionAutor}
onChange={this.onChangeQuestionAutor}
/>
</div>
<div className="form-group">
<label>Question: </label>
<input type="text"
className="form-control"
value={this.state.question}
onChange={this.onChangeQuestion}
/>
</div>
<div>
<ul>
{this.answerList()}
</ul>
</div>
<div className="form-group">
<button type="button" onClick = {this.onAddItem} className="btn btn-primary"> Add answer </button>
</div>
<div className="form-group">
<input type="submit" value="submit Question" className="btn btn-primary" />
</div>
</form>
</div>
)
}
}
when i send the data to the database i always have in the answer fields empty string and false no update has been done.
thanks a lot,
Boubker ELAMRI
You’re modifying the list, so react doesn’t know it’s changed. You need to create a new array first, before setting the state
const list = Array.from(this.state.answerOptions)
list.push(newAnswer)

Update value with user input

I have an input field that i would like to update that users first name when you click submit for that specific user. right now i have an alert in handleSubmit to just see if its working. and it is but i want it to update the actual users name.
Displays Users on separate cards. would like the edit button to work for each user.
class User extends Component {
constructor(props) {
super(props);
this.state = {
names: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
render() {
return (
<div className='UserCard'>
<div className='UserCardTop'>
<form className='Submit' onSubmit={this.handleSubmit}>
<input
type="text"
name="names"
value={this.state.names}
ref={this.input}
onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
<h3>{this.props.name} {this.props.last}</h3>
<div className='ImageContainer'>
<img alt="image" width="80" src={this.props.image} />
</div>
</div>
<div className='UserCardBottom'>
<h5>{this.props.email}</h5>
<h5>{this.props.cell}</h5>
<h5>{this.props.city}, {this.props.state}</h5>
</div>
</div>
)
}
}
export default User
App.js
import React, { Component } from "react";
import axios from "axios";
import User from './User'
import Filter from './Filter.js'
class App extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
searchTerm: '',
alphabetical: 'az'
};
this.handleChange = this.handleChange.bind(this);
this.handleFilter = this.handleFilter.bind(this);
}
componentDidMount() {
axios.get("https://randomuser.me/api/?page=3&results=10&seed=abc")
.then(response => {
console.log(response.data.results);
this.setState({ users: response.data.results });
})
.catch(error => {
console.log(error);
});
}
handleFilter(filterInput) {
this.setState(filterInput)
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
let sortedUsers;
if (this.state.alphabetical === "az") {
console.log("sorted");
sortedUsers = this.state.users.sort((a, b) =>
a.name.first > b.name.first ? 1 : -1
);
}
let filteredUsers = sortedUsers;
if (this.state.searchTerm)
filteredUsers = this.state.users.filter(u =>
u.name.first.startsWith(this.state.searchTerm) || u.name.last.startsWith(this.state.searchTerm)
);
const userNames = filteredUsers.map(u => {
return <User
key={u.email}
name={u.name.first}
last={u.name.last}
image={u.picture.large}
email={u.email}
city={u.location.city}
state={u.location.state}
cell={u.cell}
/>;
});
return (
<div>
<Filter
searchTerm={this.state.searchTerm}
onFilter={this.handleFilter}
></Filter>
<select
name="alphabetical"
value={this.state.alphabetical}
onChange={this.handleChange}>
<option value="az">
A to Z
</option>
<option value="za">Z to A</option>
</select>
{userNames}
</div>
);
}
}
export default App
A simple solution would be to add an onChangeFirst callback prop to your User component, which would be invoked with the new first name when handleSubmit() is called:
User.js
handleSubmit(event) {
event.preventDefault();
if(this.props.onChangeFirst) {
/* Pass this users state (with names data) to onChange callback */
this.props.onChangeFirst(this.state.names);
}
}
The onChangeFirst callback prop would be "wired up" to the App component so that when it is called (from inside User.js), the corresponding user object (in App.js) is updated with the newFirstName. You could add the onChangeUserFirstName() function as shown below, which updates the first field of the user object in the App components state:
App.js
/* Helper function that updates first name state for matching user */
const onChangeUserFirstName = (user, newFirstName) => {
/* Updates state with newly mapped users to new array, where first name
if updated to that supplied in changes.names for existing user match */
this.setState({ users : this.state.users.map(u => {
return (u === user) ? { ...u, first : newFirstName } : u;
});
});
}
const userNames = filteredUsers.map(u => {
/* Add (newFirstName) => onChangeUserFirstName(u, newFirstName) */
return <User
onChangeFirst={ (newFirstName) => onChangeUserFirstName(u, newFirstName) }
key={u.email}
name={u.name.first}
last={u.name.last}
image={u.picture.large}
email={u.email}
city={u.location.city}
state={u.location.state}
cell={u.cell}
/>;
});

unable to perform dynamic search in react app using static data

I am performing sort , filter and pagination on my react app which displays data from a json file which includes movies data. I am able to fetch data from input box but unable to setState and also console log searchKey and movies.
Below is the code for App.js and Hello.js. App component has both sort and search functions.
App.js
import data from './data.json';
class App extends Component {
constructor() {
super();
this.state = {
movies: data.movies, sort_term: '', searchKey: '', filterList: '',
};
this.onSorting = this.onSorting.bind(this);
this.onSearchMovie = this.onSearchMovie.bind(this);
}
onSorting = (e) => {
let term = 'Title';
let option = e.target.value;
let sortedList = [...this.state.movies].sort((a, b) => {
return (option == 'asc' ? (a[term] <= b[term] ? -1 : 1) :
(a[term] >= b[term] ? -1 : 1))
});
this.setState({ sort_term: term });
this.setState({ movies: sortedList });
}
onSearchMovie(e) {
let key = e;
console.log(key);
this.setState({searchKey : key });
console.log(searchKey);
let list = movies.filter(m =>{
return m.Title.toLowerCase().includes(searchKey.toLowerCase());
});
this.setState({movies:list});
}
render() {
const { movies } = this.state;
if (!movies.length) {
return (
<div className="container">
<h2>loading...</h2>
</div>
);
}
else {
return (
<div>
<Hello sort_term={this.state.sort_term}
onSorting={this.onSorting}
onSearch={this.onSearchMovie} />
<br />
<Table movies={this.state.movies} />
</div>
);
}
}
}
Hello.js
class Hello extends Component {
constructor(props) {
super(props);
this.state = { inputField: '', }
this.onSubmitTitle = this.onSubmitTitle.bind(this);
this.getTitle = this.getTitle.bind(this);
}
onSubmitTitle(e){
e.preventDefault();
this.props.onSearch(this.state.inputField);
this.setState({ inputField: '' });
}
getTitle(e){
this.setState({ inputField: e.target.value });
// console.log('---');
// console.log(this.state.inputField);
}
render() {
const { sort_term, onSorting } = this.props;
return (
<div className="header">
Database
<ul className="navLeft">
<li>
<form onSubmit={this.onSubmitTitle}>
<input type="search" onChange={this.getTitle} value={this.state.inputField}
className="search-bar"
placeholder="Type for search..." />
</form>
</li>
<li >
<form >
<select
onChange={onSorting}
className="searchBar">
<option value="desc" >Sort Title(Z - A)</option>
<option value="asc">Sort Title(A - Z)</option>
<option value="descDirector">Sort Director(Z - A)</option>
<option value="ascDirector">Sort Director(A - Z)</option>
</select>
</form>
</li>
</ul>
</div>
);
}
}
You got couple of issues:
You got some undefined variables here:
onSearchMovie(e) {
let key = e;
console.log(key);
this.setState({ searchKey: key });
console.log(searchKey);
let list = movies.filter(m => {
return m.Title.toLowerCase().includes(searchKey.toLowerCase());
});
this.setState({ movies: list });
}
like `searchKey` and `movies`.
setState is asynchronous, so doing this:
this.setState({ sort_term: term });
this.setState({ movies: sortedList });
Is the same as doing this:
this.setState({
sort_term: term,
movies: sortedList
});
With that saying, this code block may not work as expected:
onSearchMovie(e) {
let key = e;
console.log(key);
this.setState({ searchKey: key });
console.log(searchKey);
let list = movies.filter(m => {
return m.Title.toLowerCase().includes(searchKey.toLowerCase());
});
this.setState({ movies: list });
}
Because as mentioned above, setState is asynchronous. so this.state.searchKey may not be what you think when you access it the next line.
Either use the key variable or use the setState callback which will trigger after setState has done.
this.setState({someKey: someValue}, () => {console.log(this.state.someKey)})
You can read more about it in the docs Why is setState giving me the
wrong value?.
Another thing you may not know is that when you use onSubmit on a
form you actually need to trigger the submit. Since you don't have
any submit button you can do it with the enter key. so while you
are focused on the input press the enter key and the form will
get submitted.
Another thing i would do, is to display and update a filteredMovis
list instead of the movies list directly because once you filter
out items then you can't get them back. so when you do filtering you
do it on movies but updating the filteredMovis list without
removing items from the original movies list.
Here is a working and running example:
const data = {
movies: [
{
id: 1,
Title: "wonder woman"
},
{
id: 2,
Title: "kill bill"
},
{
id: 3,
Title: "world war z"
},
{
id: 4,
Title: "pixels"
}
]
};
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = { inputField: "" };
this.onSubmitTitle = this.onSubmitTitle.bind(this);
this.getTitle = this.getTitle.bind(this);
}
onSubmitTitle(e) {
e.preventDefault();
this.props.onSearch(this.state.inputField);
this.setState({ inputField: "" });
}
getTitle(e) {
this.setState({ inputField: e.target.value });
// console.log('---');
// console.log(this.state.inputField);
}
render() {
const { onSorting } = this.props;
return (
<div className="header">
Database
<ul className="navLeft">
<li>
<form onSubmit={this.onSubmitTitle}>
<input
type="text"
onChange={this.getTitle}
value={this.state.inputField}
className="search-bar"
placeholder="Type for search..."
/>
</form>
</li>
<li>
<form>
<select onChange={onSorting} className="searchBar">
<option value="desc">Sort Title(Z - A)</option>
<option value="asc">Sort Title(A - Z)</option>
<option value="descDirector">Sort Director(Z - A)</option>
<option value="ascDirector">Sort Director(A - Z)</option>
</select>
</form>
</li>
</ul>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
movies: data.movies,
filteredMovis: data.movies,
sort_term: "",
searchKey: "",
filterList: ""
};
this.onSorting = this.onSorting.bind(this);
this.onSearchMovie = this.onSearchMovie.bind(this);
}
onSorting = e => {
let term = "Title";
let option = e.target.value;
let sortedList = [...this.state.movies].sort((a, b) => {
return option == "asc"
? a[term] <= b[term]
? -1
: 1
: a[term] >= b[term]
? -1
: 1;
});
this.setState({
sort_term: term,
filteredMovis: sortedList
});
};
onSearchMovie(key) {
const { movies } = this.state;
let list = movies.filter(m => {
return m.Title.toLowerCase().includes(key.toLowerCase());
});
this.setState({ filteredMovis: list, searchKey: key });
}
render() {
const { filteredMovis, movies } = this.state;
if (!movies.length) {
return (
<div className="container">
<h2>loading...</h2>
</div>
);
} else {
return (
<div>
<Hello
sort_term={this.state.sort_term}
onSorting={this.onSorting}
onSearch={this.onSearchMovie}
/>
<br />
{filteredMovis.map(movie => <div key={movie.id}>{movie.Title}</div>)}
</div>
);
}
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<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="root"></div>

Categories