I have the problem when I use the Reactjs, I'm really new to Reactjs, so maybe it's a easy problem
I want to use the class ClickButton in the UserInfo,but I don't know how to change the name through props
import React, { PropTypes } from 'react';
import { Button } from 'antd';
import { connect } from 'react-redux';
import styles from './ClickButton.less';
const ClickButton = ({ todos,dispatch }) => {
const userinforclick = () => {
dispatch({
type: 'todos/clickbutton',
payload: !todos['click_button'],
});
};
return (
<span>
< span type="primary" className={ styles.show } onClick={ userinforclick.bind(this) } > {this.props.name} < /span >
</span>
);
};
function clickbutton({ todos }){
return{
todos:todos,
}
}
export default connect(clickbutton)(ClickButton)
and i use the ClickButton in UserInfo:
import React from 'react'
import styles from './Userinfo.less'
import ClickButton from '../../components/Button/ClickButton'
import { connect } from 'react-redux';
import { Spin } from 'antd'
const Userinfo = ({ todos,dispatch }) => {
const { userinfo, userinfoloading, click_button } = todos;
if(userinfoloading) {
return <Spin />;
}
const renderList = () => {
return(
<div className={ styles.userInfodiv}>
<div>
<span className={ styles.userInfoTitle }>userinfo</span>
</div>
<div className = { styles.slice }></div>
<div className = { styles.userInfoBody}>
<div className = { styles.userInfoSubBody }>
<span>username:</span>
<span>{userinfo[0]['username']}</span>
</div>
<div className = { styles.userInfoSubBody }>
<span>number:</span>
{ click_button ? <span>{userinfo[0]['phone']}</span> : <input type="text" value={userinfo[0]['phone']} /> }
<ClickButton name="john" />
</div>
</div>
</div>
);
};
return (
<div>
{ renderList() }
</div>
);
};
function mapStateToProps({ todos }) {
return {
todos: todos,
};
}
export default connect(mapStateToProps)(Userinfo);
Here's something that actually works (although I removed the todos and such but you can add them in easily):
class RenderList extends React.Component {
render() {
return (<span> {this.props.name} </span>);
}
}
class App extends React.Component {
render() {
return (<div>
<RenderList name="John"/>
</div>)
}
}
ReactDOM.render(<App/>,document.getElementById("app"));
Related
how to add an action when the add button is clicked then the item will display the product?
This code does not display the product when clicked
I've been fiddling with it but it's still an error, who knows, someone here can help me and fix the code and explain it
cartAction.js
import {ADD_TO_CART} from './ActionType';
export const addToCart = (items) =>{
return{
type: ADD_TO_CART,
items //I'm confused about what to do in the action payload here
}
}
cartReducer.js
import ImgT from './images/image-product-1-thumbnail.jpg';
import {ADD_TO_CART} from './ActionType';
const initState = {
items: [
{id:1,title:'title',
brand:cc',
images:ImgT,
desc:'helo world',
price:125.00}
],addItems:[],
total:0
}
const cartReducer= (state = initState,action)=>{
if(action.type === ADD_TO_CART){
return {...state, addItems:state.addItems} //I'm confused about what to do in the action payload here
}
return state
}
export default cartReducer;
cart.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
class Cart extends Component {
render() {
return (
<div>
{this.props.Items.map(item =>{
<div key={item.id}>
{/* <img src={item.images} /> */}
<p>{item.title}</p>
<h4>brand: {item.brand}</h4>
<p>{item.price}</p>
</div>
})
}
</div>
);
}
}
const mapToProps = (state ) =>{
return{
Items:state.addItems}
}
export default connect(mapToProps)(Cart);
Home.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Cart from './Cart';
import {addToCart} from './cartAction';
class Home extends Component{
handleClick = () =>{
this.props.addToCart()
}
render(){
let item = this.props.items.map(item =>{
return(
<div className='card' key={item}>
<img style={{width:'10rem'}} src={item.images}/>
<p className='card-title '>{item.title}</p>
<h2 className='card-title fs-4'>{item.brand}</h2>
<button onClick={() => this.handleClick()} className='btn btn-primary'>Add to cart</button>
<h3 className='fs-5'>{item.price}</h3>
</div>
)
})
return(
<div className="container">
<h3>Home</h3>
{item}
<Cart/>
</div>
)
}
}
const mapToProps = (state) => {
return{
items:state.items,
}
}
const mapDispatchToProps = (dispatch) => {
return{
addToCart: () => dispatch(addToCart())}
}
export default connect(mapToProps,mapDispatchToProps)(Home);
For some reason, when i render InventoryItem component inside InventoryPage component, dispatch is returned as undefined, but when i render it inside any other component it works perfectly.
Here's InventoryItem:
// REDUX
import { connect } from 'react-redux';
import { addItem } from '../../../Redux/reducers/cart/actions/cartActions.js';
// REUSABLE COMPONENTS
import { Button } from '../button/button.jsx';
export const InventoryItem = ({ drilledProps, dispatch }) => {
const { name, price, imageUrl } = drilledProps;
return (
<div className="collection-item">
<div
className="image"
style={{
background: `url(${imageUrl})`
}}
/>
<div className="collection-footer">
<span className="name">{name}</span>
<span className="price">${price}</span>
</div>
<Button
handler={() => dispatch(addItem(drilledProps))}
modifier="_inverted"
type="button"
text="ADD TO CART"
/>
</div>
);
};
export default connect(null)(InventoryItem);
When i render it here, dispatch returns undefined:
// REDUX
import { connect } from 'react-redux';
import { categorySelector } from '../../../../Redux/reducers/inventory/selectors/inventorySelectors.js';
// COMPONENTS
import { InventoryItem } from '../../../reusable-components/inventory-item/inventory-item.jsx';
const InventoryPage = ({ reduxProps: { categoryProps } }) => {
const { title: category, items } = categoryProps;
return (
<div className="collection-page">
<h2 className="title">{category}</h2>
<div className="items">
{
items.map((item) => (
<InventoryItem key={item.id} drilledProps={item}/>
))
}
</div>
</div>
);
};
const mapStoreToProps = (currentStore, ownProps) => ({
reduxProps: {
categoryProps: categorySelector(ownProps.match.params.categoryId)(currentStore)
}
});
export default connect(mapStoreToProps)(InventoryPage);
When i render it here it works perfectly:
// COMPONENTS
import InventoryItem from '../../../../reusable-components/inventory-item/inventory-item.jsx';
export const InventoryPreview = ({ title, items }) => {
return (
<div className="collection-preview">
<h1 className="title">{title}</h1>
<div className="preview">
{items
.filter((item, index) => index < 4)
.map((item) => (
<InventoryItem key={item.id} drilledProps={item} />
))}
</div>
</div>
);
};
Thanks for the help in advance!
You are importing the unconnected component, the connected component exports as default so you should do:
//not import { InventoryItem }
import InventoryItem from '../../../../reusable-components/inventory-item/inventory-item.jsx';
when you do export const InventoryItem = then you import it as import {InventoryItem} from ... but when you import the default export: export default connect(... then you import it as import AnyNameYouWant from ...
So, as the title suggests, Cards component is receiving props from UserPosts, as well as it's connected to the store to dispatch an action. But it looks like this is not working at all. Connecting a component is not working for me. Maybe I am missing something? Can someone show me the correct way to do it. I'm trying to delete a post on clicking on the delete button.
Here is the code.
UserPosts
import React, { Component } from "react"
import { getUserPosts, getCurrentUser } from "../actions/userActions"
import { connect } from "react-redux"
import Cards from "./Cards"
class UserFeed extends Component {
componentDidMount() {
const authToken = localStorage.getItem("authToken")
if (authToken) {
this.props.dispatch(getCurrentUser(authToken))
if (this.props && this.props.userId) {
this.props.dispatch(getUserPosts(this.props.userId))
} else {
return null
}
}
}
render() {
const { isFetchingUserPosts, userPosts } = this.props
return isFetchingUserPosts ? (
<p>Fetching....</p>
) : (
<div>
{userPosts &&
userPosts.map(post => {
return <Cards key={post._id} post={post} />
})}
</div>
)
}
}
const mapStateToPros = state => {
return {
isFetchingUserPosts: state.userPosts.isFetchingUserPosts,
userPosts: state.userPosts.userPosts,
userId: state.auth.user._id
}
}
export default connect(mapStateToPros)(UserFeed)
Cards
import React, { Component } from "react"
import { connect } from "react-redux"
import { deletePost } from "../actions/userActions"
class Cards extends Component {
handleDelete = postId => {
this.props.dispatch(deletePost(postId))
}
render() {
const { _id, title, description } = this.props.post
return (
<div className="card">
<div className="card-content">
<div className="media">
<div className="media-left">
<figure className="image is-48x48">
<img
src="https://bulma.io/images/placeholders/96x96.png"
alt="Placeholder image"
/>
</figure>
</div>
<div className="media-content" style={{ border: "1px grey" }}>
<p className="title is-5">{title}</p>
<p className="content">{description}</p>
<button className="button is-success">Edit</button>
<button
onClick={this.handleDelete(_id)}
className="button is-success"
>
Delete
</button>
</div>
</div>
</div>
</div>
)
}
}
const mapStateToProps = () => {
return {
nothing: "nothing"
}
}
export default connect(mapStateToProps)(Cards)
deletePost
export const deletePost = (id) => {
return async dispatch => {
dispatch({ type: "DELETING_POST_START" })
try {
const deletedPost = await axios.delete(`http://localhost:3000/api/v1/posts/${id}/delete`)
dispatch({
type: "DELETING_POST_SUCCESS",
data: deletedPost
})
} catch(error) {
dispatch({
type: "DELETING_POST_FAILURE",
data: { error: "Something went wrong" }
})
}
}
}
Should be something like this:
const mapDispatchToProps(dispatch) {
return bindActionCreators({ deletePost }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Cards)
And then call it as a prop:
onClick={this.props.deletePost(_id)}
I used to make this code work out for my search component but after the on submit is called, I receive this error which never happened before, does anyone have any clue???
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
import React, { Component } from "react";
import axios from "axios";
import { Redirect } from "react-router-dom";
import { Consumer } from "../context";
class Search extends Component {
constructor() {
super();
this.state = {
productTitle: "",
apiUrl: "*******************************",
redirect: false
};
}
findProduct = (dispatch, e) => {
e.preventDefault();
axios
.post(
`${this.state.apiUrl}`,
JSON.stringify({ query: this.state.productTitle })
)
.then(res => {
dispatch({
type: "SEARCH_TRACKS",
payload: res.data.output.items
});
this.setState({ items: res.data.output.items, redirect: true });
})
.catch(err => console.log(err));
};
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
const { redirect } = this.state;
if (redirect) {
return <Redirect to="/searchresult" />;
}
return (
<Consumer>
{value => {
const { dispatch } = value;
return (
<div>
<form onSubmit={this.findProduct.bind(this, dispatch)}>
<div className="form-group" id="form_div">
<input
type="text"
className="form-control form-control-md"
placeholder="...محصولات دسته یا برند مورد نظرتان را انتخاب کنید"
name="productTitle"
value={this.state.productTitle}
onChange={this.onChange}
/>
<button className="btn" type="submit">
<i className="fas fa-search" />
</button>
</div>
</form>
</div>
);
}}
</Consumer>
);
}
}
import React, { Component } from 'react'
import axios from 'axios'
const Context = React.createContext();
export const axiosDashboard = () => {
const URL = (`*****************`);
return axios(URL, {
method: 'POST',
data: JSON.stringify({refresh:"true"}),
})
.then(response => response.data)
.catch(error => {
throw error;
});
};
const reducer = (state, action) => {
switch(action.type){
case 'SEARCH_TRACKS':
return {
...state,
items: action.payload,
heading: 'Search Results'
};
default:
return state;
}
}
export class Provider extends Component {
state = {
dispatch:action => this.setState(state => reducer(state, action))
}
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
}
}
export const Consumer = Context.Consumer
import React, { Component } from 'react'
import { Consumer } from '../context'
import SearchResult from './SearchResult'
import './Search.css'
class Tracks extends Component {
render() {
return (
<Consumer>
{value => {
const { items } = value
if(items === undefined || items.length === 0){
return 'hello'}
else{
return(
<React.Fragment>
<div id='products_search'>
<div className='container'>
<div className="row justify-content-end">
{items.map(item => (
<SearchResult
key={item.id}
id={item.id}
title={item.name}
current_price={item.current_price}
lowest_price={item.lowest_price}
store_name={item.store_name}
thumb={item.thumb_url}/>
))}
</div>
</div>
</div>
</React.Fragment>
)
}
}}
</Consumer>
)
}
}
export default Tracks
import React from 'react'
import {Link} from 'react-router-dom'
import './Search.css'
const SearchResult = (props) => {
const {title,current_price,lowest_price,thumb,id,store_name} = props
return (
<div className="col-md-3" id="searchresult">
<img src={thumb} alt=""/>
<div className="sexy_line"></div>
<p className="muted">{store_name}</p>
<h6>{title}</h6>
<p>{lowest_price}</p>
<Link to={`products/item/${id}`}>
<button type="button" className="btn btn-light rounded-pill">{
new Intl
.NumberFormat({style: 'currency', currency: 'IRR'})
.format(current_price)
}</button>
</Link>
</div>
)
}
export default SearchResult
Maximum update depth exceeded.
This means that you are in a infinit loop of re rendering a component.
The only place where I can see this is possible to happen is in this part
if (redirect) {
return <Redirect to="/searchresult" />;
}
Maybe you are redirecing to the a route that will get the same component that have the redirect.
Please check if you aren't redirecting to the same route as this component and provide your routes and what is inside Consumer.
I am a beginner in React js and I'm trying to implement Context Provider in React js. But while I'm not getting the perfect output.
I am storing contact info in context.js which will act as Context Provider and in App.js I imported it in App.js then in Contacts.js I Consumed the Consumer and got the value but still, I'm getting the blank page and I'm not sure why I cannot bind the contact component in Context provider
Context.js
import React, {Component} from 'react';
const Context = React.createContext();
export class Provider extends Component {
state = {
contacts: [{
id: 1,
name: "dasd B",
email: "asdas#gmail.com",
phone: "dsadas"
}
};
render() {
debugger
return (
<Context.Provider value={this.state}>
{this.props.childern}
</Context.Provider>
);
}
}
export const Consumer = Context.Consumer;
App.js
import React, { Component } from 'react';
import Header from './components/Header';
import Contacts from './components/Contacts'
import 'bootstrap/dist/css/bootstrap.min.css';
import { Provider } from './Context'
class App extends Component {
render() {
return (
<Provider>
<div className="App">
<div className="container">
<Contacts />
</div>
</div>
</Provider>
);
}
}
export default App;
Contacts.js
import React, { Component } from 'react'
import Contact from './Contact';
import { Consumer } from '../Context';
class Contacts extends Component {
deleteContact = id => {
const { contacts } = this.state;
const newContacts = contacts.filter(contact => contact.id!== id);
this.setState({
contacts: newContacts
});
};
render() {
debugger
return(
<Consumer>
{value => {
const { contacts } = value;
return (
<React.Fragment >
{contacts.map(contact => (
<Contact
key = {contact.id}
contact={contact}
deleteClickHandler = {this.deleteContact.bind(this, contact.id)}>
</Contact>
))}
</React.Fragment>
);
}}
</Consumer>
);
}
}
export default Contacts;
Contact.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class Contact extends Component {
state = {
showContactinfo : false
};
onDeleteClick = () => {
this.props.deleteClickHandler();
}
onEditClick() {
}
render() {
const { name, email, phone } =this.props.contact;
const { showContactinfo } = this.state;
return (
<div className="card card-body mb-3">
<h4>{name}
{showContactinfo ? (
<div className="float-right">
<i
onClick= {this.onEditClick}
style={{cursor: 'pointer', fontSize: 'medium'}}
className="fas fa-edit mr-3"></i>
<i
onClick= {this.onDeleteClick}
style={{cursor: 'pointer', fontSize: 'medium'}}
className="fa fa-trash-alt"></i>
</div>):
<i className="fa fa-sort-down float-right"
style={{cursor: 'pointer'}}
onClick={() =>
this.setState({ showContactinfo: !this.state.showContactinfo})}></i>}
</h4>
{showContactinfo ? (
<ul className="list-group">
<li className="list-group-item">Email: {email}</li>
<li className="list-group-item">Phone: {phone}</li>
</ul>) : null}
</div>
)
}
}
Contact.propTypes = {
contact: PropTypes.object.isRequired,
deleteClickHandler: PropTypes.func.isRequired
}
export default Contact;