OnClick function not rendering a component in react-redux - reactjs

I have been working to solve this problem for hours now. In my App component to add a new list on clicking a button i am calling a redux action as a prop which will push a new list into the list array. I don't see any errors with my code and this piece of code has worked for another component but not in the main App component. Is there anything i am doing wrong?
import React, { Component } from 'react';
import List from './components/list.react.js';
import './App.css';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import {addList} from './ListAction.js';
import PropTypes from 'prop-types'
import AddIcon from './AddIcon.png';
class App extends Component {
constructor(props){
super(props);
}
getLists=()=>{
return(
this.props.lists.map((list)=>{
return(
<List key={list.id} id={list.id} ></List>
);
})
)}
render() {
debugger;
let ListId=1;
return (
<div className="Content">
<div className="Header-Wrapper"><h1>React Redux App</h1></div>
<div className="Boxes">
<List id={ListId} />
<div>{this.getLists}</div>
<div className="wrapper">
<button className = "NewCard" onClick={this.props.addList}>
<img src={AddIcon} alt="Add-Icon"></img>
Add a new List
</button>
</div>
</div>
</div>
);
}
}
App.propTypes={
lists:PropTypes.array.isRequired
}
function mapStateToProps(state){
return({lists:state.Lists})
}
function mapDispatchToProps(dispatch){
return bindActionCreators({addList:addList},dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

Edited:
use {this.getLists()} instead of {this.getList}.
(since Amir Aleahmad comment was correct answer i edited the my first)

Related

Why does react display my functional component at the bottom of my page?

My main page looks like this :
import React from "react";
import { Fragment } from "react";
import ModalA from "../components/Modal/ModalOptionA";
export default class AePage extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Fragment>
<div className="grid-intro">
<div className="text-intro">
Some Text
</div>
<div className="modal-component-insert">
<ModalA show={true}/>
</div>
<div className="text-outro">
Some text
</div>
</div>
</Fragment>
)
}
}
And my component looks like this :
import React from "react";
import ReactDOM from "react-dom";
const Modal = ({ show, closed}) => {
return (
ReactDOM.createPortal(
<>
<div className="modal">
My Component
</div>
</>,
document.body
)
)
}
export default Modal;
The code above display something like :
Some Text
Some Text
My Component
Why does my component not display between the texts ? Is there a specific way for React to display this component between my divs ?
That is what ReactDOM.createPortal is for. It will always move things to the bottom of the DOM. That way, you can then position it above everything else using CSS.
It seems you don't really need that, so I'd just replace your code for the Modal component with:
import React from "react";
const Modal = ({ show, closed}) => {
return (
<div className="modal">
My Component
</div>
)
}
export default Modal;

ReactJs --- sending props to children causing issue in rendering in children. UI Rendering not happening "NewsLatest.js"

One component Landing.js has following code::
import React, { Component } from 'react'
import NewsSearch from '../NewsSearch/NewsSearch';
import NewsLatest from '../NewsLatest/NewsLatest';
import './Landing.css';
import axios from 'axios';
class Landing extends Component {
state={
newsList: []
}
componentDidMount(){
axios.get(`https://api.nytimes.com/svc/topstories/v2/home.json?api-key=7cK9FpOnC3zgoboP2CPGR3FcznEaYCJv`)
.then(res=> {
this.setState({newsList: res.data.results});
});
}
render() {
// console.log(this.state.newsList);
return (
<div className="landing text-center text-white">
<h1>News Portal</h1>
<div className="news-search">
<NewsSearch />
</div>
<div className="news-latest">
<NewsLatest newsList={this.state.newsList}/>
</div>
</div>
)
}
}
export default Landing;
When sending props to NewsLatest component, 2 values are getting passed: first as undefined and then when value comes then an array with the values.
In the "NewsLatest.js" file code is :::
import React, { Component } from 'react';
// import PropTypes from 'prop-types';
class NewsLatest extends Component {
newsTitle = (
this.props.newsList.map(item => (<h2>{item.title}</h2>))
)
render() {
console.log(this.props.newsList);
return (
<div>
<h2>News Latest....</h2>
{this.newsTitle}
</div>
);
}
}
export default NewsLatest;
Nothing is rendering on the UI. I dont know how to handle that. Kindly suggest something.
The issue you are facing is that you are not rendering anything (per se) cos newsTitle does not return anything.
In your code, newsTitle is an object but you need to make it a function.
Modifying NewsLatest should fix this though
import React, { Component } from 'react';
// import PropTypes from 'prop-types';
class NewsLatest extends Component {
newsTitle = () => (
this.props.newsList.map(item => (<h2>{item.title}</h2>))
)
render() {
console.log(this.props.newsList);
return (
<div>
<h2>News Latest....</h2>
{this.newsTitle()}
</div>
);
}
}
export default NewsLatest;

Problem with the id of the items in shopping cart application in react

I am developing a shopping cart application . I am using redux and routing . There are mainly 3 pages Home,shop and About. I am adding authentication to the shop page and after successful authentication the user can enter into the shop page. In the shop page there are items which we can add to cart . totally i have 3 items in my shop page.whats my problem is when i am clicking add to cart for 1 st item it is displaying 3 items. I know the problem is with the id's of the items. But I am struggling from past one hour to resolve it.
Thanks in advance.
//App.js
import React ,{Component} from 'react';
import './App.css';
import Navigation from './Step1/Navbar'
import Home from './Step1/Home'
import Shop from './Step1/Shop'
import About from './Step1/About'
import Login from './LoginAuthentication/Loginform'
import {BrowserRouter as Router,Route} from 'react-router-dom'
import {connect} from 'react-redux'
const mapStateToProps=(state)=>{
return{
isLogin:state.isLogin
}
}
class App extends Component {
render(){
return (
<Router>
<div className="App">
<Navigation/>
<Route path="/" exact component={Home}/>
<Route path="/about" component={About}/>
<Route path="/shop"
render={() =>(
this.props.isLogin ? <Shop/> : <Login/>
) }
/>
</div>
</Router>
);
}
}
export default connect(mapStateToProps,null)(App);
//shop template.js
import React from 'react'
//import logo from '../cricket bat.jpg'
import Displaylist from '../Components/DisplayList'
const Shop_template=(props)=> {
return (
<div className="container">
<div className="row">
<div className="col-sm-6">
<div className="card-body">
<h4 className="card-title">{props.cardtitle}</h4>
<p className="card-text">{props.description}</p>
<h3>Price :{props.currency}{props.price}</h3>
<button type="button" onClick={props.cartHandler} className="btn btn-primary">Add to cart</button>
</div>
</div>
<div className="col-sm-6">
<Displaylist/>
</div>
</div>
</div>
)
}
export default Shop_template
//shop.js --> i am updating the state in shop.js to redux state
import React, { Component } from 'react'
import ShopTemplate from './Shop_template'
import {connect} from 'react-redux'
import {action2} from '../Actions/action1'
const mapDispatchToProps=(dispatch)=>({
CartHandler:(details)=>dispatch(action2(details))
})
class Shop extends Component {
state={
items:[
{id:1,cardtitle:'SSS Bat',description:'A stroke to score',currency:'$',price:100},
{id:2,cardtitle:'One upon a wall street',description:'A way to investment',currency:'$',price:50},
{id:3,cardtitle:'mi powerbank 10000mah',description:'Keep charged always',currency:'$',price:200}
]
}
cartHandler=()=>{
this.props.CartHandler(this.state.items)
}
render() {
const info=this.state.items.map((detail)=>{
return <ShopTemplate
cardtitle={detail.cardtitle}
description={detail.description}
currency={detail.currency}
price={detail.price}
key={detail.id}
cartHandler={this.cartHandler}
/>
})
return (
<div>
{info}
</div>
)
}
}
export default connect(null,mapDispatchToProps)(Shop)
/
/reducer.js
import {LOGINCHECK} from '../Constants/actiontypes'
import {ADDTOCART} from '../Constants/actiontypes'
const initialState={
isLogin:false,
items:[]
}
const reducer1=(state=initialState,action)=>{
//console.log(state)
if(action.type===LOGINCHECK){
return Object.assign({},state,{isLogin:true})
}
if(action.type===ADDTOCART){
return Object.assign({},state,{items:state.items.concat(action.payload)})
}
return state
}
export default reducer1
//DisplayList.js
import React from 'react'
import Display from './Display'
import {connect} from 'react-redux'
const mapStateToProps=(state)=>{
return{
items:state.items
}
}
const DisplayList=({items})=>{
console.log(items.body)
return(
<div>
{items.map(it=>{
return(
<Display iteminfo={it.body} key={it.body.id}/>
)
})
}
</div>
)
}
export default connect(mapStateToProps,null)(DisplayList)
//Display.js
import React from 'react'
const Display=({iteminfo:{id,cardtitle, description,currency,price}}) =>{
return (
<div>
<h4>{cardtitle}</h4>
<p>{description}</p>
<h3>{currency}{price}</h3>
<button type="button" className="btn btn-danger">Remove From cart</button>
</div>
)
}
export default Display
I can see too many problems in your source code,
first of all, namings can be better now it's confusing.
your shop items are in Shop component state but it has to be inside your redux module
initialState = {
items: ["your items should be here"]
}
of course, its because you are hardcoding your shop items. you may want to Get shop items from an API.
when you click on add to cart button you have to pass itemId to action. (right now you don't know which item is going to add to cart ).
and then inside reducer action.payload.itemId will be itemId that is added to cart then you can do something like this
const foundItem = state.items.find(it => it.id === action.payload.itemId);
now you found item in your products(items) array,
you can add this item to another array called basket or cart that represents items user added.
for the next step you want to add an inventory and quantity property to see how many items the user wants and how many do you have in your inventory
if you want a more detailed description don't hesitate to ask

imported component is not displayed

i've a component that i import, but its not displayed on the page.
this is my app.js file. i imported the <player/>component but it is not getting displayed properly on the browser.
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import { player } from "./player";
class App extends Component {
render() {
return (
<div className="App">
<div>
<player />
</div>
</div>
);
}
}
export default App;
this is the contents of the player.js
import React from "react";
import { Button } from "evergreen-ui";
export default class player extends React.Component {
constructor(...args) {
super(...args);
this.state = {
shoot: 0
};
}
shoot() {
this.setState.shoot = Math.floor(Math.random() * Math.floor(3));
}
render() {
return (
<div>
<h1>hello there</h1>
<h1>{this.state.shoot}</h1>
<Button onClick={() => this.shoot}>Shoot another
value</Button>
</div>
);
}
}
In your code, you've exported your player component as a default export
export default class player extemds React.Component
But in your import of it in the other file, you're importing it as a named export
import { player } from "./player";
Try importing it without the curly braces as you would with a default export
import player from "./player";
You are doing two mistakes:
1. Importing the component in the wrong way
2. Rendering the component in the wrong way
Solution
The component should be imported without the curly braces
The react component "player" is supposed to start with capital letters i.e. it should be renamed as Player
Below is the working code I have tried in my local machine. It only modifies App.js
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import Player from "./player"; // imported without curly braces and with capital first letter
class App extends Component {
render() {
return (
<div className="App">
<div>
<Player /> {/* Rendering the correct way */}
</div>
</div>
);
}
}
export default App;
Sidenote
In player.js, you are setting the state in the wrong fashion, it won't work because:
setState is a method and not a object
this is not binded with method shoot. It will throw error something like "cannot read this of undefined" or something
Modify your player.js as following:
import React from "react";
import { Button } from "evergreen-ui";
export default class player extends React.Component {
constructor(...args) {
super(...args);
this.state = {
shoot: 0
};
}
shoot = ()=>{
this.setState({
shoot: Math.floor(Math.random() * Math.floor(3)),
});
}
render() {
return (
<div>
<h1>hello there</h1>
<h1>{this.state.shoot}</h1>
<Button onClick={() => this.shoot()}>Shoot another
value</Button>
</div>
);
}
}
You have two main issues:
1) You export as default and then your import is wrong.
If you export as:
export default class player extemds React.Component
Then you need to import as:
import player from "./player";
2) Components must start uppercase, otherwise React thinks that they are simple HTML tags and not components.
So you must change player to Player everywhere

ReactComponent Button value won't render on my react app

I've got a simple React App going on. My index.js file looks, of course, like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
Going deeper, my App.js file declares an App extends Compoennt class, which contains my to-be-rendered elements and their functions:
import React, { Component } from "react";
import logo from "./SmartTransit_logo.png";
import MyButton from "./components/MyButton";
import "./App.css";
import { isWallet, helloWorld } from "./services/neo-service";
class App extends Component {
state = {
inputValue: ""
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Smart Transit Live Demo</h1>
</header>
<div style={{ width: 500, margin: "auto", marginTop: 10 }}>
<MyButton
buttonText="My Button"
onClick={ params => {helloWorld();}}
/>
</div>
</div>
);
}
}
export default App;
And the declaration of MyButton from /components/MyButton:
import React, { Component } from "react";
import PropTypes from "prop-types";
class MyButton extends Component {
render() {
return (
<button className="MyButton"
value = {this.props.buttonText}
>
{this.props.children}
</button>
);
}
}
MyButton.propTypes = {
buttonText: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
};
export default MyButton;
Finally, the declaration for helloWorld() is done like so (NOTE: neon-js is an npm package I'm using):
import { wallet } from "#cityofzion/neon-js";
export function isWallet(address) {
console.log(wallet.isAddress(address));
return wallet.isAddress(address);
}
export function helloWorld() {
console.log("Hello world");
return 1;
}
My problem is that the resulting Button doesn't get its value text rendered, and although it gets the CSS code for it just fine, it appears empty!
Not only that, but pressing it doesn't log a "Hello World" in the console, as it should, so it's even disconnected from its onClick function.
Any idea on what I'm doing wrong?
Buttons don't receive a "value" prop. The text inside of the button element is what gives it its text.
The button does appear to accept children to use as button text, but no children is actually being passed down to it. this.props.children is the content between JSX tags when the component is rendered.
React doesn't add the event handlers to elements automatically. You have to pass them along yourself in order for them to be properly triggered.
With that in mind, here's how you should render your button in App:
<MyButton onClick={() => helloWorld()}>
My Button
</MyButton>
And here's how MyButton's code should look:
class MyButton extends Component {
render() {
return (
<button className="MyButton" onClick={this.props.onClick}>
{this.props.children}
</button>
)
}
}
As you can see, the buttonText prop is no longer required; that's what the children prop is for.
You need to define super(props) in class constructor when you are going to use this.props
constructor(props) {
super(props);
}
Define this in MyButton component.
The problem is, you are not calling onClick method from mybutton component and button take it's value between it's opening and closing tag.
Use this code:
this.props.onClick()}> {this.props.buttonText}

Resources