Second Component cannot reload data - javascript

Hi i have problem using reactjs to reload the second component in parent component.
I have some 3 file 1 parent component 2 child component to make simple chat website.
The problem is my component Chatroom was not reload/change the data when i click the Chatlist in the second time.
This is my parent.js
import React, { useContext } from 'react'
import $ from 'jquery'
import Wrapper from '../components/wrapper'
import ChatList from './chat-list'
import ChatRoom from './chat-room'
export default class extends React.Component {
constructor(props) {
super(props)
this.state = {
login: 0,
user: null,
tokenChat: '',
roomChat: '',
isToken: false
}
this.clickChat = this.clickChat.bind(this)
}
componentDidMount() {
$('body').addClass('menu-position-side menu-side-left')
}
componentWillUnmount() {
$('body').removeClass('menu-position-side menu-side-left')
}
clickChat(token, room) {
let self = this
self.setState({
tokenChat: token,
roomChat: room,
isToken: true
})
}
render() {
return (
<Wrapper {...this.props} title="Dashboard" selected="dashboard" padding={false}>
{this.state.login == 1 &&
<div className="content-i">
<div className="content-box">
<div className="full-chat-w">
<div className="full-chat-i">
<div className="full-chat-left">
<div className="os-tabs-w">
<ul className="nav nav-tabs upper centered">
...
</ul>
</div>
<ChatList clickChat={this.clickChat} />
</div>
<div className="full-chat-middle">
{
this.state.isToken == false ?
null
:
<ChatRoom token={this.state.tokenChat} room={this.state.roomChat} />
}
</div>
<div className="full-chat-right">
<div className="user-intro">
<div className="avatar"><img alt="" src="/static/doctor-theme/img/avatar1.jpg" /></div>
<div className="user-intro-info">
<h5 className="user-name">John Mayers</h5>
<div className="user-sub">San Francisco, CA</div>
<div className="user-social"><i className="os-icon os-icon-twitter"></i><i className="os-icon os-icon-facebook"></i></div>
</div>
</div>
<div className="chat-info-section">
<div className="ci-header"><i className="os-icon os-icon-documents-03"></i><span>Shared Files</span></div>
<div className="ci-content">
<div className="ci-file-list">
<ul>
<li>Annual Revenue.pdf</li>
<li>Expenses.xls</li>
<li>Business Plan.doc</li>
</ul>
</div>
</div>
</div>
<div className="chat-info-section">
<div className="ci-header"><i className="os-icon os-icon-documents-07"></i><span>Shared Photos</span></div>
<div className="ci-content">
<div className="ci-photos-list">
<img alt="" src="/static/doctor-theme/img/portfolio9.jpg" />
<img alt="" src="/static/doctor-theme/img/portfolio2.jpg" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</Wrapper>
)
}
}
Please Help Thank you.

Related

Not able to display list items using map in reactjs?

I have a userlist which contains name and email id of each user. I want to display it using the .map() method on userlist state variable. I have created displayusers() function to display the users but I am getting failed to compile error.
Code:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
userlist:[
{'name':'Rohan Singh',
'email':'rohan#gmail.com'
},
{'name':'Mohan Singh',
'email':'mohan#gmail.com'
},
{'name':'Rakesh Roy',
'email':'rakesh#gmail.com'
},
{'name':'Sunil Shah',
'email':'sunil#gmail.com'
}]
}
}
displayusers(){
return this.state.userlist.map( user => {
return(
<div className="item-card">
<div className="sub">
<div className="type">Username: {user.name}</div>
<div className="members">Email: {user.email}</div>
</div>
<div className="del-wrap">
<img src={require("../../images/cancel.svg")}/>
</div>
</div>
);
})
}
render() {
return(
<div className="users-wrap">
<h1>Users</h1>
<div className="task-content">
<div className="user-wrap">
<div className="users">
{this.displayusers()}
</div>
</div>
</div>
</div>
);
}
}
export default App;
I think you forgot about adding a key attribute to the element and there's missing </div> closing tag in your map function.
See the corrected code:
displayusers(){
return this.state.userlist.map( user => {
return(
<div className="item-card" key={user.name}>
<div className="sub">
<div className="type">Username: {user.name}</div>
<div className="members">Email: {user.email}</div>
</div>
<div className="del-wrap">
<img src={require("../../images/cancel.svg")}/>
</div>
</div>
);
});
}
You need to bind your displayusers function to this. You can do that in the constructor.
Update your code as following:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
userlist:[
{'name':'Rohan Singh',
'email':'rohan#gmail.com'
},
{'name':'Mohan Singh',
'email':'mohan#gmail.com'
},
{'name':'Rakesh Roy',
'email':'rakesh#gmail.com'
},
{'name':'Sunil Shah',
'email':'sunil#gmail.com'
}]
};
this.displayusers = this.displayusers.bind(this); // you need to add this line
}
displayusers(){
return this.state.userlist.map((user, index) => {
return(
<div className="item-card" key={index}>
<div className="sub">
<div className="type">Username: {user.name}</div>
<div className="members">Email: {user.email}</div>
</div>
<div className="del-wrap">
<img src={require("../../images/cancel.svg")}/>
</div>
);
})
}
render() {
return(
<div className="users-wrap">
<h1>Users</h1>
<div className="task-content">
<div className="user-wrap">
<div className="users">
{this.displayusers()}
</div>
</div>
</div>
</div>
);
}
}
export default App;

React & Typescript: Cannot read property '0' of undefined

I recently moved from .jsx to .tsx, and I'm having issues (before moving to typescript, was all working well). The first error is at line: "<Modal show={this.state.isOpen[key]} onClose={this.handleToggleModal.bind(__this,key)}>". I suspect there's something related to typescript, but I don't know what. Anybody can help me?
// TaskCard.tsx
//Dependencies
import * as React from 'react';
//Copmponents
import Modal, {ModalProps} from './Modal';
import Input from './Input';
import {IBoard} from './Board';
import PostComment from './PostComment';
export interface IComments{
body: string,
from: string,
date: string,
hour: string
}
export interface ITask{
board: string,
duedate: string,
tag: string,
tagClass: string,
tagText: string,
body: string,
risk: string,
responsable: string
comments: IComments[]
}
export interface TaskProps{
tasks: ITask[]
boards: IBoard[]
}
export interface TaskState{
isOpen: {}
}
class TaskCard extends React.Component<TaskProps, TaskState>{
constructor(props) {
super(props);
this.state = {
isOpen: props.isOpen
};
}
handleToggleModal(key) {
this.state.isOpen[key] = !this.state.isOpen[key];
this.setState(this.state.isOpen);
}
render(){
const { tasks, boards } = this.props;
let __this = this;
return(
tasks && tasks.map(
(tasks, key) =>
<div key={key} className="v-margin no-margin-top card-contour medium" onClick={this.handleToggleModal.bind(__this,key)}>
<div className="row middle-xs caption">
<div className="col-xs-6 no-padding">
<div className="row middle-xs">
<img className="img_icn no-padding-left" src="./assets/img/icn_calendar.svg" alt=""/>
<p className="txt-tertiary-color">{tasks.duedate}</p>
</div>
</div>
<div className="col-xs-6 no-padding">
<div className="row end-xs middle-xs">
<div className={tasks.tagClass + " tag tag_box center-align"}>
<p>{tasks.tag}</p>
<span className="tag_hint">{tasks.tagText}</span>
</div>
</div>
</div>
</div>
<div className="row middle-row v-padding">
<p>{tasks.body}</p>
</div>
<div className="row middle-xs caption">
<div className="col-xs-9 no-padding">
<div className="row middle-xs">
<img className="img_icn no-padding-left" src="./assets/img/icn_target.svg" alt=""/>
<p className="txt-tertiary-color">Riesgos: {tasks.risk}%</p>
</div>
</div>
<div className="col-xs-3 no-padding">
<div className="row middle-xs end-xs">
<img className="img_icn no-padding-left" src="./assets/img/icn_comments.svg" alt=""/>
<p className="txt-tertiary-color">{tasks.comments.length}</p>
</div>
</div>
</div>
<Modal show={this.state.isOpen[key]} onClose={this.handleToggleModal.bind(__this,key)}>
<div className="modal_container">
<section className="modal_section">
<div className="row middle-xs no-margin-left no-margin-right modal_section_title">
<object width="20px" height="20px" data="./assets/img/icn_objetive-blue.svg"></object>
<div className="col-xs start-xs">
<h4 className="semi-bold">Objetivo</h4>
</div>
</div>
<div className="col-xs-12 modal_section_content">
<p>{tasks.body}</p>
</div>
</section>
<section className="modal_section">
<div className="row middle-xs no-margin-left no-margin-right modal_section_title">
<object width="20px" height="20px" data="./assets/img/icn_target-blue.svg"></object>
<div className="col-xs start-xs">
<h4 className="semi-bold">Target</h4>
</div>
</div>
<div className="col-xs-12 modal_section_content">
<p>Riesgos / Problemas = {tasks.risk}%</p>
<div className="table v-margin">
<div className="row middle-xs">
<div className="col-xs">
<p className="table_head">Fecha de vencimiento</p>
<p className="table_body">{tasks.duedate}</p>
</div>
<div className="col-xs">
<p className="table_head">Tipo de objetivo</p>
<p className="table_body">{tasks.tagText}</p>
</div>
<div className="col-xs">
<p className="table_head">Responsable</p>
<p className="table_body">{tasks.responsable}</p>
</div>
<div className="col-xs-12 v-margin no-margin-bottom">
<p className="table_head">Estado de objetivo</p>
<div className="row middle-xs">
{
boards && boards.map(
(boards, board) =>
<div key={board} className="col-xs-3">
<Input name="state" type="radio" classNameCustom="input_radio"
checked={boards.id == tasks.board} value={boards.id} id={boards.id}/>
<label htmlFor={boards.id}>{boards.name}</label>
</div>
)
}
</div>
</div>
</div>
</div>
</div>
</section>
<section className="modal_section">
<div className="row middle-xs no-margin-left no-margin-right modal_section_title">
<object width="20px" height="20px" data="./assets/img/icn_activity-blue.svg"></object>
<div className="col-xs start-xs">
<h4 className="semi-bold">Actividad</h4>
</div>
</div>
<div className="col-xs-12 modal_section_content">
{
tasks.comments.length!=0 ?(
tasks.comments.map((comments, i) => {
return(
<div key={i} className="comment">
<div className="comment_box">
<p>{comments.body}</p>
</div>
<div className="comment_data row no-margin middle-xs">
<div className="col-xs start-xs">
<p>{comments.from}</p>
</div>
<div className="col-xs end-xs">
<p>{comments.date} a las {comments.hour} hs.</p>
</div>
</div>
</div>
)
})
):null
}
</div>
</section>
</div>
<PostComment />
</Modal>
</div>
)
)
}
}
export default TaskCard;
And here is the Modal component
//Modal.tsx file
//Dependencies
import * as React from 'react';
export interface ModalProps{
onClose: any,
show: boolean,
children: any
}
export default class Modal extends React.Component<ModalProps>{
handleStopPropagation = (e) =>{
e.stopPropagation();
}
render(){
const {onClose, show, children} = this.props;
// Render nothing if the "show" prop is false
if(!this.props.show) {
return null;
}
return (
<div className="modal_bkg" onClick={this.handleStopPropagation}>
<div className="modal_bkg_container row middle-xs center-xs">
<div className="modal card">
<div className="right-align modal_close">
<button className="btn btn_close" onClick={this.props.onClose}>x</button>
</div>
{this.props.children}
</div>
</div>
</div>
);
}
}
I'm unable to run the code at the moment, but as far as I can see the TaskCard.render function is using Array.map function, which is executing a callback function for every task item.
And there is a problem, because in the callback this is not the this you think it is :). According to documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map you can use map overload that accepts this.
I believe that if you do
return(tasks && tasks.map(
(tasks, key) => <div>put your component markup here</div>,
this)
);
inside TaskCard.render function you should see the error no more.
A friend helped me with this and now it's working. The first problem was the state "isOpen" at start always is undefined so, that's why runtime was throwing error "Cannot read property '0' of undefined". So now, "isOpen" is and empty object and the final constructor looks like this:
constructor(props) {
super(props);
this.state = {
isOpen: {}
};
}
After this, another error was "boards.map is not a function" and that was because I was passing the array "boards" as object. Changing for "board" was enought. So the final code was:
boards && boards.map(
(board, key) =>
<div key={key} className="col-xs-3">
<Input name="state" type="radio" classNameCustom="input_radio"
checked={board.id == task.board} value={board.id} id={board.id}/>
<label htmlFor={board.id}>{board.name}</label>
</div>
)
Anyway, thanks for trying to help me. Regards!

React local storage

I made a counting app that when you click you level and get gold, then you spend the gold in the store, but I need the data stay in local storage. I used the getMax() function to display the gold in the store page but I need the gold to update on the store page as well.
Sorry I'm quite new to react
My Home.js file
import React, {Component} from 'react';
import '../App.css';
import darkalien from '../assets/darkgray__0000_idle_1.png';
import darkalien2 from '../assets/darkgray__0033_attack_3.png';
import darkalien3 from '../assets/darkgray__0039_fire_5.png';
var style = {
color: 'black',
fontSize: 20
};
var style2 ={
color: '#daa520',
fontSize: 20
}
export default class Home extends Component{
constructor(props) {
super(props);
this.state = {
i: 0,
j: 1,
k: 0,
max: 10,
maxf: 2,
maxi: 10
}
}
getMax(){
return this.state.max
}
onClick(e) {
e.preventDefault();
var level = this.state.j;
this.setState({i: this.state.i + 1});
this.setState({k: this.state.k + 1});
if(this.state.i >= this.state.max){
this.setState({j: this.state.j + 1});
this.setState({i: this.state.i});
this.setState({k: this.state.k});
if(this.state.j === this.state.maxf){
this.setState({maxf: this.state.maxf + 1});
this.setState({max: this.state.max + 10});
}
this.setState({i: this.state.i = 0});
}
}
render(){
return(
<header>
<div className="container" id="maincontent" tabIndex="-1">
<div className="row">
<div className="col-lg-12">
<div className="intro-text">
<p className="name" style={style} id="demo3">Level {this.state.j}</p>
<p className="name" id="demo4" style={style}>Points: {this.state.k}</p>
<p className="name" style={style2} id="demo5">Gold: {this.state.max}</p>
<img id="picture" className="img-responsive" src={darkalien} alt="alien-img" onClick={this.onClick.bind(this)} height="150" width="150"/>
<progress id="demo2" value={this.state.i} max={this.state.max}></progress>
<h1 className="name">Click me!</h1>
<hr className="glyphicon glyphicon-star-empty"></hr>
<span className="skills">Gain Experience ★ Get Coins ★ Purchase Armor</span>
</div>
</div>
</div>
</div>
</header>
);
}
}
My store.js file
import React, {Component} from 'react';
import blaster from '../assets/blaster_1.png';
import blaster2 from '../assets/blaster_3.png';
import alienSuit from '../assets/predatormask__0000_idle_1.png';
import alienHair from '../assets/alien_predator_mask_0007_hair_profile.png';
import Home from '../components/Home';
export default class Store extends Component{
render(){
var home = new Home
var max = home.getMax()
return(
<section id="portfolio">
<div className="container">
<div className="row">
<div className="col-lg-12">
<h3>Armor and Weopon Store<span> Gold: {max} </span></h3>
</div>
</div>
<div className="row text-center">
<div className="col-md-3 col-sm-6 hero-feature">
<div className="thumbnail">
<img src={blaster} alt=""/>
<div className="caption">
<h3>Reggae Blaster</h3>
<p>
Buy Now! More Info
</p>
</div>
</div>
</div>
<div className="col-md-3 col-sm-6 hero-feature">
<div className="thumbnail">
<img src={blaster2} alt=""/>
<div className="caption">
<h3>Juicy Blaster</h3>
<p>
Buy Now! More Info
</p>
</div>
</div>
</div>
<div className="col-md-3 col-sm-6 hero-feature">
<div className="thumbnail">
<img src={alienSuit} alt=""/>
<div className="caption">
<h3>Full Body Reggae Armor</h3>
<p>
Buy Now! More Info
</p>
</div>
</div>
</div>
<div className="col-md-3 col-sm-6 hero-feature">
<div className="thumbnail">
<img src={alienHair} alt=""/>
<div className="caption">
<h3>Reggae Spikes</h3>
<p>
Buy Now! More Info
</p>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
This.setState has a callback function after you update the state.
It should be something similar to this.
Use this.setState({...}, () => localStorage.setItem('gold', whatever value gold should be);

ReactJs Cannot read property 'props' of undefined

I have react js code of inner most child component like this
import React from 'react'
import { addToCart } from 'actions/cart'
export default (props) => {
const { line_item, cart} = props
// const oClick = line_item.oClick.bind(line_item)
const handleClick = (id) => this.props.dispatch(addToCart(id, 1))
// *I am getting error above line*
return (
<div>
<ul className="ul-reset">
<li>
<div className="cart-prod-wrapper cf">
<div className="cart-image-wrapper">
<div className="cart-image">
<a href="#"><img src="#" alt="Product One"/>
</a>
</div>
</div>
<div className="cart-details">
<div className="cart-name">
{line_item.variant.name}
</div>
<div className="cart-price">{line_item.variant.price}</div>
</div>
<div className="cart-qty">
<div className="cart-qty-name">QTY:</div>
<div className="cart-qty-value">
<div class="minus"><span>-</span></div>
{line_item.quantity}
<div class="plus">
<span value = { line_item.variant.id } onClick={handleClick(line_item.variant.id)} >+</span></div>
</div>
</div>
<div className="cart-total">
<div className="cart-total-name">Total</div>
<div className="cart-total-value">{line_item.variant.price * line_item.quantity}</div>
</div>
</div>
</li>
</ul>
</div>
)
}
i want to perform to call an action using dispatch
and code of parent presentation component is line
export default (props) => {
const { account, cart, readMore1} = props
return (
<li>
{ !cart.isFetching && cart.line_items.map(
(line_item, i) => <CartPreview key = {i} line_item= {line_item} cart ={cart} />)
}
</li>
)
}
can any on please guide me to solve this error
Edit
const mapStateToProps = (state) => {
return {
account: getAccount(state),
cart: getCart(state),
classToSend: getReadmore(state),
authenticityToken: getAuthenticityToken(state)
}
}
export default connect(mapStateToProps)(HeaderContainer)
May be this could help
import React from 'react'
import { connect } from 'react-redux' // import connect from redux
import { addToCart } from 'actions/cart'
// name component to wrap it with connect
const MyComponent = (props) => {
const { line_item, cart} = props
return (
<div>
<ul className="ul-reset">
<li>
<div className="cart-prod-wrapper cf">
<div className="cart-image-wrapper">
<div className="cart-image">
<a href="#"><img src="#" alt="Product One"/>
</a>
</div>
</div>
<div className="cart-details">
<div className="cart-name">
{line_item.variant.name}
</div>
<div className="cart-price">{line_item.variant.price}</div>
</div>
<div className="cart-qty">
<div className="cart-qty-name">QTY:</div>
<div className="cart-qty-value">
<div class="minus"><span>-</span></div>
{line_item.quantity}
<div class="plus">
// used arrow function
<span value = { line_item.variant.id } onClick={() => props.dispatch(addToCart(line_item.variant.id, 1)} >+</span></div>
</div>
</div>
<div className="cart-total">
<div className="cart-total-name">Total</div>
<div className="cart-total-value">{line_item.variant.price * line_item.quantity}</div>
</div>
</div>
</li>
</ul>
</div>
)
}
export default connect()(MyComponent); // connect dispatch to component

Reactjs How to pass the props of current page into child page

This is Clients_info.js
In this component's props, it has several values.
And now I want to pass all the props in this component to the Modalbox component.
I know how to pass value from the current state to child component in render function as props. But....from props to props...
How could I make that? Thanks!
import React from "react";
import Modalbox from './Client_modal'
require('../../css/Clients.scss');
var $ = require ('jquery');
export default class Clients_info extends React.Component {
constructor(props) {
super(props);
}
//Invoked once, both on the client and server, immediately before the initial rendering occurs.
componentWillMount(){
}
render() {
return(
<div id='tabbox-order' className='clients_info'>
<div id='clientsInfo_wrapper'>
<div id='clientsInfo_row'>
<div id='ava_wrapper'>
<img id='clietnsInfo_avatar'></img>
<p>{this.props.client.name}</p>
</div>
<div id='infor_wrapper'>
<p><i class="material-icons">email</i> Email: {this.props.client.email}</p>
<p><i class="material-icons">phone</i> Phone: {this.props.client.phone}</p>
<p><i class="material-icons">location_on</i> Address: {this.props.client.loc}</p>
<p><i class="material-icons">my_location</i> Zip Code: {this.props.client.zip}</p>
</div>
</div>
<div id='key' >
<i class="material-icons">vpn_key</i>{this.props.client.key}
</div>
<div id='Cutting' ></div>
<div>
<h4>Pets Information</h4>
{ this.props.pets.map(function(pet) {
return(
<div>
<div className='row'key={pet.id}>
<div className='col-md-3' >avatar</div>
<div className='col-md-3' >{pet.petName}</div>
<div className='col-md-3' >{pet.breed}</div>
<div className='col-md-3' >{pet.age}</div>
</div>
<div id='pet-detail'>
<p>Extra Information:</p>
<input placeholder='This dog is crazy!!!'>
</input>
</div>
</div>
)
})
}
</div>
<div id='Cutting' ></div>
<Modalbox/>
</div>
</div>
);
}
}
<Modalbox pets={ this.props.pets }/>
Should do the job

Categories

Resources