Problem:
I want to write a program that adds a new card when the button is pressed. I can connect and change states, but no new cards. (There is no problem that the value in the state is constant. The important thing is the formation of the new card).
There are two different components above. When the button is pressed (same state), I want a new card to be created. But I couldn't write the code.
card.jsx
import React from 'react'
import CardStyle from '../cardStyle/cardStyle';
class Card extends React.Component {
constructor(props){
super(props);
this.state = {
isLoading: true,
imageUrl: null,
fullName: null,
job: null
};
}
clickEvent = () => {
this.setState({
fullName: 'Furkan',
job: 'Software engineer'
});
}
render() {
let {isLoading, imageUrl, fullName, job} = this.state;
return (
<div>
<CardStyle
isLoading={isLoading}
imageUrl = {imageUrl}
fullName = {fullName}
job = {job}
clicked = {this.clickEvent}
/>
<button onClick={this.clickEvent}>ADD PERSON</button>
</div>
)
}
}
export default Card;
cardStyle.jsx
import React, { Component } from 'react'
import classes from "./cardStyle.css";
import Wrap from "../../Wrap/Wrap";
class CardStyle extends Component {
state = {
image: null,
fullName: null,
job: null
};
createCard = () => {
return(
<div className={classes.Card}>
<div className={classes.Image}>{this.props.imageUrl}</div>
<div className={classes.Title}>{this.props.fullName}</div>
<div className={classes.Job}>{this.props.job}</div>
</div>
)
};
render() {
return (
<Wrap>
{this.createCard()}
</Wrap>
)
}
}
export default CardStyle;
If you want to create a new card every time you click your button, you should create cards array which maps every new card to a component. This way you will get a new card with every click instead of modifying the old card.
import React from 'react'
import CardStyle from '../cardStyle/cardStyle';
class Card extends React.Component {
constructor(props){
super(props);
this.state = {
cards: [
{
isLoading: true,
imageUrl: null,
fullName: null,
job: null
}
]
};
}
clickEvent = () => {
const cards = [
...this.state.cards,
{
fullName: 'Furkan',
job: 'Software engineer'
}
]; // This will create a new array from the old one with a new additional value
this.setState({ cards });
}
render() {
const { cards } = this.state;
return (
<div>
{cards.map((card, index) => (
<CardStyle
key={index}
isLoading={card.isLoading}
imageUrl = {card.imageUrl}
fullName = {card.fullName}
job = {card.job}
/>
)}
<button onClick={this.clickEvent}>ADD PERSON</button>
</div>
)
}
}
export default Card;
When you're calling clickEvent method, you do not adding another value to the state, but you're overwrite existing: imgUrl and fullName.
You have to create array of cards, and display them by map method inside return.
If first card is blank for now, you can start from empty array in state cards: [], and display CardStyle component only if this.state.cards.length > 0.
Related
I am building a recipe app and I have an api that fetches me recipes based on what i type in. the issue is that whenever i type the search phrase and search, it makes the state super unstable by sending in insane amounts of objects into the state (normally it should be like 10-12 results. These objects are repeat of each other (you can see it in the screenshot i have attached). The code is provided below, can anyone show me why this might be so?
import React, { Component } from 'react';
import RecipeDisplay from '../RecipeDisplay/RecipeDisplay';
import Form from '../Form/Form';
import './RecipeUI.css';
import uuid from 'uuid/v4';
export default class RecipeUI extends Component {
constructor(props) {
super(props);
this.state = {
food: [ '' ],
RecipeUI: [ { title: '', thumbnail: '', href: '' } ]
};
this.search = this.search.bind(this);
}
search(x) {
this.setState({ food: x });
}
componentDidUpdate() {
let url = `https://api.edamam.com/search?q=${this.state
.food}&app_id=cf711&app_key=b67d194436b01d1f576aef`;
fetch(url)
.then((response) => {
return response.json();
})
.then((data) =>
data.hits.map((n) => {
let wow = {
key: uuid(),
title: n.recipe.label,
thumbnail: n.recipe.image,
href: n.recipe.url
};
this.setState({ RecipeUI: [ ...this.state.RecipeUI, wow ] });
console.log(this.state);
})
);
}
render() {
return (
<div className="RecipeUI">
<div className="RecipeUI-header">
<h1>Welcome to the Recipe Fetcher</h1>
<Form search={this.search} />
</div>
<div className="RecipeUI-RecipeDisplay">
{this.state.RecipeUI.map((recipe) => (
<RecipeDisplay
key={recipe.key}
title={recipe.title}
thumbnail={recipe.thumbnail}
ingredients={recipe.ingredients}
href={recipe.href}
/>
))}
</div>
</div>
);
}
}
Please, try this as you are concatenating the existing items in state with that of the items that are being brought from search results, the state has got lot of data. Assuming you need only the search results in state, here is the code below:
import React, { Component } from 'react';
import RecipeDisplay from '../RecipeDisplay/RecipeDisplay';
import Form from '../Form/Form';
import './RecipeUI.css';
import uuid from 'uuid/v4';
export default class RecipeUI extends Component {
constructor(props) {
super(props);
this.state = {
food: '',
RecipeUI: []
};
this.search = this.search.bind(this);
}
search(x) {
this.setState({ food: x });
}
componentDidUpdate() {
let url = `https://api.edamam.com/search?q=${this.state.food}&app_id=cf7165e1&app_key=
946d6fb34daf4db0f02a86bd47b89433`;
fetch(url).then((response) => response.json()).then((data) => {
let tempArr = [];
data.hits.map((n) => {
let wow = {
key: uuid(),
title: n.recipe.label,
thumbnail: n.recipe.image,
href: n.recipe.url
};
tempArr.push(wow);
});
this.setState({RecipeUI:tempArr})
});
}
render() {
return (
<div className="RecipeUI">
<div className="RecipeUI-header">
<h1>Welcome to the Recipe Fetcher</h1>
<Form search={this.search} />
</div>
<div className="RecipeUI-RecipeDisplay">
{this.state.RecipeUI.map((recipe) => (
<RecipeDisplay
key={recipe.key}
title={recipe.title}
thumbnail={recipe.thumbnail}
ingredients={recipe.ingredients}
href={recipe.href}
/>
))}
</div>
</div>
);
}
}
I'm trying to get some map over some data and render it as a card style component.
The data structure is as follows within my user array (all fake data)
and this is the code...
import React from "react";
import OverlayContent from "./OverlayContent";
import { onCountryClick } from "../Scene3D/AppSignals";
import Portal from "./Portal";
import "./style.scss";
class Overlay extends React.Component {
constructor(props) {
super(props);
this.state = { overlay: false, users: [], country: [] };
this.openOverlay = this.openOverlay.bind(this);
this.closeOverlay = this.closeOverlay.bind(this);
}
openOverlay() {
this.setState({ overlay: true });
}
closeOverlay() {
this.setState({ overlay: false });
}
onCountryClick = (country, users) => {
this.openOverlay();
this.setState({ users: [users], country });
};
componentDidMount() {
this.onCountrySignal = onCountryClick.add(this.onCountryClick);
}
componentWillUnmount() {
this.onCountrySignal.detach();
}
render() {
const country = this.state.country;
const users = this.state.users;
console.log(users);
return (
<div className="btn-container">
{this.state.overlay && (
<Portal>
<div>
<h1>{country}</h1>
{users &&
users.map(user => (
<div className="user_container">
<h1 key={user.id} className="user_name">
{user.favouriteQuote}
</h1>
</div>
))}
<button className="btn" onClick={this.closeOverlay}>
Close
</button>
</div>
</Portal>
)}
</div>
);
}
}
export default Overlay;
When mapping on this user array it doesn't appear to give me access to the actual user data I need. Is it because I have an array within an array?
onCountryClick = (country, users) => {
this.openOverlay();
this.setState({ users: [users], country });
};
Is users an array? If so remove the brackets here or map through the first element. users[0].map()
Trying to get my head around props so forgive me if its a silly mistake. I am trying to pass all of my data into one variable and pass that out into props (using {item.text} and {item.key}), however, my ".map" isn't picking up anything and there's a bunch of errors, what's wrong with my code?
The problem lays specifically here in this block of code
createList(list) {
return <li>{list.text}</li>
}
render() {
var entries = this.state.list
var finalEntries = entries.props.map(this.createList)
Here is the code in full
import React from "react";
import "./App.css";
import { isTemplateElement } from "#babel/types";
class TodoListt extends React.Component {
state = {};
constructor(props) {
super(props);
this.state = {
userInput: "",
list: [],
};
}
changeUserInput(input) {
this.setState({
userInput: input
})
}
addToList(input) {
let listArray = this.state.list;
listArray.push(input);
var newItem = {
text: listArray,
key: Date.now()
};
this.setState(prevState => {
return {
list: prevState.list.concat(newItem)
};
});
this.setState({
list: listArray
})
}
createList(list) {
return <li>{list.text}</li>
}
render() {
var entries = this.state.list
var finalEntries = entries.props.map(this.createList)
return (
<div className="to-do-list-main">
<input
onChange={(e) => this.changeUserInput(e.target.value)}
value={this.state.userInput}
type="text"
/>
<button onClick={() => this.addToList(this.state.userInput)}>Press me</button>
<ul>
{this.testingSetup()}
</ul>
</div>
);
}
}
export default TodoListt;
You can use the spread operator to add to an existing array. Simply add a new object to the array in the state, and then clear the user input, ready for another item. Based on your code, here's a simple example of adding to a state list (haven't run myself, so just check for syntax errors and such):
import React from "react";
import "./App.css";
import { isTemplateElement } from "#babel/types";
class TodoList extends React.Component {
state = {};
constructor(props) {
super(props);
this.state = {
userInput: "",
list: [],
};
}
changeUserInput(input) {
this.setState({
userInput: input
})
}
addToList() {
const { list, userInput } = this.state;
// Add item to state list using spread operator and clear input
this.setState({
list: [...list, {text:userInput, key: Date.now()}],
userInput: ""
});
}
render() {
return (
<div className="to-do-list-main">
<input
onChange={(e) => this.changeUserInput(e.target.value)}
value={this.state.userInput}
type="text"
/>
<button onClick={() => this.addToList()}>Press me</button>
<hr/>
{/* For each item in the list, render the contents */}
{this.state.list.map(item => (
<div key={item.key}>
<h3>{item.text}</h3>
<p>Time: {item.key}</p>
</div>
))}
</div>
);
}
}
export default TodoList;
I'm making a movie search page. When I search something, it goes through the data base and find the very first match and display on the page. However, I want to create a function, so when I click next, page displays next movie in the data base. My code follows:
import React, { Component, PropTypes } from 'react';
import SearchBar from './Bar/index.js';
import SearchResult from './Result/index.js';
import axios from 'axios';
import './index.css';
class SearchArea extends Component {
constructor(props) {
super(props);
this.state = {
searchText: '',
searchResult: {},
result: false,
count: 0
};
}
handleSearchBarChange(event) {
this.setState({searchText: event.target.value});
}
handleSearchBarSubmit(event) {
event.preventDefault();
const movie = this.state.searchText;
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=c6cd73ec4677bc1d7b6560505cf4f453&language=en-US&query=${movie}&page=1&include_adult=false`)
.then(response => {
if(response.data.results.length >= 0) {
const i = 0;
const {
title,
overview,
release_date: releaseDate
} = response.data.results[this.state.count];
const posterPath = 'https://image.tmdb.org/t/p/w154' + response.data.results[this.state.count].poster_path;
this.setState({
searchResult: {
title,
posterPath,
overview,
releaseDate
},
result: true
});
}
else {
this.setState({
searchResult: {
title: 'No Result',
overview: 'No Overview Available',
posterPath: ''
},
result: true
});
}
})
}
handleSearchNext(event) {
this.handelSearchBarSubmit.overview = response.data.results[1];
}
handleResultClose() {
this.setState({
searchResult: {},
result: false
});
}
render() {
return (
<div>
<SearchBar
value = {this.state.searchText}
onChange = {this.handleSearchBarChange.bind(this)}
onSubmit = {this.handleSearchBarSubmit.bind(this)}
onNext = {this.handleSearchNext.bind(this)}
/>
{this.state.result &&
<SearchResult
searchResult = {this.state.searchResult}
onClose = {this.handleResultClose.bind(this)}
onAdd = {this.props.onAdd}
/>
}
</div>
);
}
}
SearchArea.propTypes = {
onAdd: PropTypes.func.isRequired
};
export default SearchArea;
I can't seem to figure out how to make handleSearchNext. Please help
EDIT
Following is the SearchBar code
import React, { PropTypes } from 'react';
import { Button } from 'semantic-ui-react';
import styles from './index.css';
const SearchBar = (props) => {
return (
<div>
<form onSubmit={(event) => props.onSubmit(event)}>
<input
className="searchBar"
type="text"
placeholder="Search Here"
value={props.value}this
onChange={(event) => props.onChange(event)}
onNext={(event) => props.onChange(event)}
onBack={(event) => props.onChange(event)}
/>
<Button className="button" type="submit">Sumbit</Button>
</form>
<Button className={styles.button} type="previous">Back</Button>
<Button className="button" type="next">Next</Button>
</div>
);
};
SearchBar.propTypes = {
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onBack: PropTypes.func.isRequired,
onNext: PropTypes.func.isRequired
};
export default SearchBar;
You could have your server respond with not only the requested title, but also the next one. That way, when you click on Next, you can immediately display the next movie without waiting for a response, while still querying it in the background by name or id (so that you have the next after it, etc.).
Edit: If I misunderstood what you meant and you already have this (it looks like you are actually querying a whole page of movies at once), you probably simply want something like
handleSearchNext(event) {
this.setState({ searchResult: response.data.results[1], result: true });
}
and handle specially the case when you hit the last item on the page.
Reading around, I see that initializing state from props in the getInitialState()/constructor can be an anti-pattern.
What is the best way of initializing state from props and managing to be consistent?
As you can see below, I'm trying to initialize my "Card" component so that I may have a likeCount and isLikedByMe states initialized. I do this so that I may have a custom like counter displayed and the text of the Like button to change, by resetting the state.
At this point, I'm doing this in the constructor, but that is the wrong way to do it. How should I manage this?
import * as React from "react";
import { CardLikeButton } from "./buttons";
export enum CardType {
None = 0,
Text,
Image
}
export interface CardMedia {
text?: string;
imageUrl?: string;
}
export interface CardDetails {
isLikedByMe: boolean;
likeCount: number;
}
export interface CardParams extends React.Props<any> {
cardType: number;
cardId: string;
cardMedia: CardMedia;
cardDetails: CardDetails;
}
export class Card extends React.Component<CardParams, CardDetails> {
state: CardDetails;
constructor(props: CardParams) {
super(props);
console.log("in card constructor");
console.log("card type: " + props.cardType);
this.state = { // setting state from props in getInitialState is not good practice
isLikedByMe: props.cardDetails.isLikedByMe,
likeCount: props.cardDetails.likeCount
};
}
componentWillReceiveProps(nextProps: CardParams) {
this.setState({
isLikedByMe: nextProps.cardDetails.isLikedByMe,
likeCount: nextProps.cardDetails.likeCount
});
}
render() {
console.log("RENDERING CARD");
// console.dir(this.props.cardDetails);
// console.dir(this.props.cardMedia);
// console.dir(this.props.cardType);
if (this.props.cardType === CardType.Text) { // status card
return (
<div className="general-card">
<p>Text card.ID: {this.props.cardId}</p>
<p>{this.props.cardMedia.text}</p>
<CardLikeButton onButClick={this.likeButtonClicked} buttonText={this.state.isLikedByMe ? "Liked" : "Like"} isPressed={this.state.isLikedByMe}/>
<p>Like count: {this.state.likeCount}</p>
</div>
);
} else { //photo card
return (
<div className="general-card">
<p>Image card.ID: {this.props.cardId}</p>
<p> {this.props.cardMedia.text} </p>
<img src={this.props.cardMedia.imageUrl} />
<br/>
<CardLikeButton onButClick={this.likeButtonClicked} buttonText={this.state.isLikedByMe ? "Liked" : "Like"} isPressed={this.state.isLikedByMe}/>
<p>Like count: {this.state.likeCount}</p>
</div>
);
}
}
likeButtonClicked = () => {
console.log('in card => like button clicked!');
var _isLikedByMe = this.state.isLikedByMe;
var _likeCount = this.state.likeCount;
if (_isLikedByMe) {
_likeCount--;
} else {
_likeCount++;
}
_isLikedByMe = !_isLikedByMe;
this.setState({
isLikedByMe: _isLikedByMe,
likeCount: _likeCount
})
}
}
Here is the main list component:
/// <reference path="../../typings/index.d.ts" />
import * as React from "react";
import * as ReactDOM from "react-dom";
import {Card} from "./card";
import {CardParams, CardType, CardMedia, CardDetails} from "./card";
var card1: CardParams = {
cardType: CardType.Image,
cardId: "card1234",
cardDetails: {
isLikedByMe: false,
likeCount: 3
},
cardMedia: {
text: "some test text; badescuga",
imageUrl: "http://www9.gsp.ro/usr/thumbs/thumb_924_x_600/2016/06/19/738742-rkx1568-lucian-sinmartean.jpg"
}
};
var card2: CardParams = {
cardId: "card35335",
cardType: CardType.Text,
cardDetails: {
isLikedByMe: true,
likeCount: 1
},
cardMedia: {
text: "some test 2 text"
}
};
var cards = [card1, card2];
ReactDOM.render(
<div>
{
cards.map((item) => {
return (
<Card key={item.cardId} cardId={item.cardId} cardType={item.cardType} cardDetails={item.cardDetails} cardMedia={item.cardMedia}/>
);
})
}
</div>,
document.getElementById("mainContainer")
);
Without getting into working with Flux, or Redux, and focusing on your question.
IMHO, state and props need to be separated, where Card only gets props, and state is managed from above. Card component will get an event handler to raise once the like button has been clicked. You could either do the "like" logic inside the Card component, and just raise the event handler with the output of that logic, for example:
this.props.likeClicked(isLikedByMe, updatedLikeCount).
Or, do the whole logic in the parent component.
I would also wrap all cards in another component.
Example:
class Card extends React.Component {
constructor(props: CardParams) {
super(props);
}
render() {
return (
<div>
<button onClick={this.likeButtonClicked}>
{this.props.isLikedByMe ? 'Unlike' : 'Like'}
</button>
<p>Like count: {this.props.likeCount}</p>
</div>
)
}
likeButtonClicked = () => {
console.log('in card => like button clicked!');
var _isLikedByMe = this.props.isLikedByMe;
var _likeCount = this.props.likeCount;
if (_isLikedByMe) {
_likeCount--;
} else {
_likeCount++;
}
_isLikedByMe = !_isLikedByMe;
if (this.props.likeUpdated) {
this.props.likeUpdated({
cardId: this.props.cardId,
isLikedByMe: _isLikedByMe,
likeCount: _likeCount
})
}
}
}
class CardList extends React.Component {
constructor(props) {
super(props)
this.state = {
// Could use es6 map
cards: {123: {isLikedByMe: false, likeCount: 3},
124: {isLikedByMe: true, likeCount: 2}}
}
}
_onLikeUpdated({cardId, isLikedByMe, likeCount}) {
const cards = Object.assign({}, this.state.cards)
cards[cardId] = {isLikedByMe, likeCount}
this.setState({cards})
}
_getCards() {
return Object.keys(this.state.cards).map(cardId => {
return <Card key={cardId}
cardId={cardId}
likeUpdated={this._onLikeUpdated.bind(this)}
{...this.state.cards[cardId]} />
})
}
render() {
return <div>
{this._getCards()}
</div>
}
}
Fiddle: https://jsfiddle.net/omerts/do13ez79/