How to select React elements in React.js? - javascript

I rendered some elements with a functional component and I'm trying to select some of the elements to log them out to the console, but it logs out null. is there a special method used to select react elements?
This is my code:
let menuIcon = <i className=" bi bi-list" id="menu-icon"></i>
let cvIcon = <i className="bi bi-caret-down-fill"></i>
export default function Navbar() {
return (
<nav>
<div id="menu">
{menuIcon}
<div id="menu-list-container">
ABOUT
STACK
CONTACT
PROJECTS
</div>
</div>
<div id="logo">
<span id="v">V</span>
<span id="s">S</span>
<span id="c">C</span>
</div>
<div id="cv-container">
<button>
<input type="button" name="cv-btn" value="RESUME" id="cv-btn"/>
{cvIcon}
</button>
<div>
Download CV
View CV
</div>
</div>
</nav>
);
}
const root = document.getElementById("root");
createRoot(root).render(<Navbar></Navbar>);
const menuList = document.getElementById("menu-list-container")
console.log(menuList)

You cannot access the DOM right away after calling render; this is an asynchronous call.
A simple example involves using a basic setTimeout to wait a second after rendering.
const { useState } = React;
const { createRoot } = ReactDOM;
const menuIcon = <i className=" bi bi-list" id="menu-icon"></i>;
const cvIcon = <i className="bi bi-caret-down-fill"></i>;
const Navbar = () => {
return (
<nav>
<div id="menu">
{menuIcon}
<div id="menu-list-container">
ABOUT
STACK
CONTACT
PROJECTS
</div>
</div>
<div id="logo">
<span id="v">V</span>
<span id="s">S</span>
<span id="c">C</span>
</div>
<div id="cv-container">
<button>
<input type="button" name="cv-btn" value="RESUME" id="cv-btn" />
{cvIcon}
</button>
<div>
Download CV
View CV
</div>
</div>
</nav>
);
};
const root = document.getElementById("root");
createRoot(root).render(<Navbar></Navbar>);
setTimeout(() => {
const menuList = document.getElementById("menu-list-container");
console.log(menuList);
}, 1000);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
Instead of a timeout, you can use a MutationObserver. This will guarantee that the element exists when it enters the DOM.
const { useState } = React;
const { createRoot } = ReactDOM;
// Adapted from: https://stackoverflow.com/a/65585776/1762224
const observe = (selector, targetNode = document.body) =>
new Promise(res => {
new MutationObserver(mutations =>
res([...mutations]
.flatMap((mutation) => [...mutation.addedNodes])
.find((node) => node.matches && node.matches(selector))))
.observe(targetNode, { childList: true, subtree: true });
});
const menuIcon = <i className=" bi bi-list" id="menu-icon"></i>;
const cvIcon = <i className="bi bi-caret-down-fill"></i>;
const Navbar = () => {
return (
<nav className="navbar">
<div id="menu">
{menuIcon}
<div id="menu-list-container">
ABOUT
STACK
CONTACT
PROJECTS
</div>
</div>
<div id="logo">
<span id="v">V</span>
<span id="s">S</span>
<span id="c">C</span>
</div>
<div id="cv-container">
<button>
<input type="button" name="cv-btn" value="RESUME" id="cv-btn" />
{cvIcon}
</button>
<div>
Download CV
View CV
</div>
</div>
</nav>
);
};
const root = document.querySelector('#root');
createRoot(root).render(<Navbar />);
observe('nav.navbar', root)
.then((menu) => {
const menuList = menu.querySelector('#menu-list-container');
console.log(menuList);
});
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

Related

How can I increment/decrement separate counters in React?

I made a ticket order system for a project, however when I want to increment the amount of one of the tickets both of the counters increase. I am not sure why this happens, but I assume it is because only one value is stored in state.
export default function Ticket() {
const [count, setState] = useState(0); // useState returns a pair. 'count' is the current state. 'setCount' is a function we can use to update the state.
function increment(e) {
//setCount(prevCount => prevCount+=1);
setState(function (prevCount) {
return (prevCount += 1);
});
}
function decrement() {
setState(function (prevCount) {
if (prevCount > 0) {
return (prevCount -= 1);
} else {
return (prevCount = 0);
}
});
}
return (
<div>
<section className="ticket-step">
<h1>TICKETS</h1>
</section>
<div className="ticket-booking is-flexbox">
<section className="ticket-content">
<ul className="tickets-tab is-flexbox">
<li>Tickets</li>
<li>Abbonementen</li>
</ul>
<div className="ticket-list-section">
<div className="ticket-list-details heading">
<div id="calender">
<h3>Datum : 30 - 10 - 2022</h3>
</div>
<div id="opening">
<h3>Openingstijden: 12:00 - 20:00 </h3>
</div>
</div>
<div className="ticket-list-details">
<div className="ticket-block">
<div className="ticket-title">
<h3>Parkeer ticket</h3>
</div>
<div className="price">
<h3>Prijs: $20</h3>
</div>
<div className="counter">
<button className="increase-amount" onClick={increment}>+</button>
<input type="text" className="amount" defaultValue="0" value={count}/>
<button className="decrease-amount" onClick={decrement}>-</button>
</div>
</div>
<div className="ticket-block">
<div className="ticket-title">
<h3>Early Horror-ticket</h3>
</div>
<div className="price">
<h3>Prijs : $59</h3>
</div>
<div className="counter">
<button className="increase-amount" onClick={increment}>+</button>
<input type="text" className="amount" defaultValue="0" value={count}/>
<button className="decrease-amount" onClick={decrement}>-</button>
</div>
</div>
</div>
</div>
</section>
<aside className="sidebar-overview">
<h1>besteloverzicht</h1>
<div className="sidebar-overview-content">
</div>
<hr/>
<div className="sidebar-overview-total">
<h3>Totaal: $0</h3>
</div>
</aside>
</div>
</div>
)
}
I tried to change useState and somehow store different states of the counters in an array, but that didn't work.
How can use the counters separately and store the state of the different buttons?
I'd say create a Button component and use that instead of adding more counters... as you might want to re-use this in different pages later as well.
Button.js
import { useState } from "react";
function Button() {
const [count, setState] = useState(0); // useState returns a pair. 'count' is the current state. 'setCount' is a function we can use to update the state.
function increment(e) {
//setCount(prevCount => prevCount+=1);
setState(function (prevCount) {
return (prevCount += 1);
});
}
function decrement() {
setState(function (prevCount) {
if (prevCount > 0) {
return (prevCount -= 1);
} else {
return (prevCount = 0);
}
});
}
return (
<div className="counter">
<button className="increase-amount" onClick={increment}>
+
</button>
<input type="text" className="amount" defaultValue="0" value={count} />
<button className="decrease-amount" onClick={decrement}>
-
</button>
</div>
);
}
export default Button;
and just re-use it in your page;
export default function Ticket() {
return (
<div>
<section className="ticket-step">
<h1>TICKETS</h1>
</section>
<div className="ticket-booking is-flexbox">
<section className="ticket-content">
<ul className="tickets-tab is-flexbox">
<li>Tickets</li>
<li>Abbonementen</li>
</ul>
<div className="ticket-list-section">
<div className="ticket-list-details heading">
<div id="calender">
<h3>Datum : 30 - 10 - 2022</h3>
</div>
<div id="opening">
<h3>Openingstijden: 12:00 - 20:00 </h3>
</div>
</div>
<div className="ticket-list-details">
<div className="ticket-block">
<div className="ticket-title">
<h3>Parkeer ticket</h3>
</div>
<div className="price">
<h3>Prijs: $20</h3>
</div>
<Button/>
</div>
<div className="ticket-block">
<div className="ticket-title">
<h3>Early Horror-ticket</h3>
</div>
<div className="price">
<h3>Prijs : $59</h3>
</div>
<Button/>
</div>
</div>
</div>
</section>
<aside className="sidebar-overview">
<h1>besteloverzicht</h1>
<div className="sidebar-overview-content">
</div>
<hr/>
<div className="sidebar-overview-total">
<h3>Totaal: $0</h3>
</div>
</aside>
</div>
</div>
)
}
Hope this helps, see how I changed the value for the input tags and useState
Let me know if it worked
import React, { useState } from "react";
export default function App() {
const [count, setState] = useState({
first: 0,
second: 0
});
function increment(type) {
setState(prev => ({
...prev,
[type]: count[type] + 1
}))
}
function decrement(type) {
if(count[type] === 0) return;
setState(prev => ({
...prev,
[type]: count[type] - 1
}))
}
return (
<div>
<section className="ticket-step">
<h1>TICKETS</h1>
</section>
<div className="ticket-booking is-flexbox">
<section className="ticket-content">
<ul className="tickets-tab is-flexbox">
<li>Tickets</li>
<li>Abbonementen</li>
</ul>
<div className="ticket-list-section">
<div className="ticket-list-details heading">
<div id="calender">
<h3>Datum : 30 - 10 - 2022</h3>
</div>
<div id="opening">
<h3>Openingstijden: 12:00 - 20:00 </h3>
</div>
</div>
<div className="ticket-list-details">
<div className="ticket-block">
<div className="ticket-title">
<h3>Parkeer ticket</h3>
</div>
<div className="price">
<h3>Prijs: $20</h3>
</div>
<div className="counter">
<button className="increase-amount" onClick={() => increment("first")}>
+
</button>
<input
type="text"
className="amount"
defaultValue="0"
value={count.first}
/>
<button className="decrease-amount" onClick={() => decrement("first")}>
-
</button>
</div>
</div>
<div className="ticket-block">
<div className="ticket-title">
<h3>Early Horror-ticket</h3>
</div>
<div className="price">
<h3>Prijs : $59</h3>
</div>
<div className="counter">
<button className="increase-amount" onClick={() => increment("second")}>
+
</button>
<input
type="text"
className="amount"
defaultValue="0"
value={count.second}
/>
<button className="decrease-amount" onClick={() => decrement("second")}>
-
</button>
</div>
</div>
</div>
</div>
</section>
<aside className="sidebar-overview">
<h1>besteloverzicht</h1>
<div className="sidebar-overview-content"></div>
<hr />
<div className="sidebar-overview-total">
<h3>Totaal: $0</h3>
</div>
</aside>
</div>
</div>
);
}
You could implement a counter hook as well as a counter component.
useCounter.jsx
import { useState } from "react";
// An enum to track whether it's increment or decrement
const actionEnum = {
INCREMENT: "increment",
DECREMENT: "decerement"
};
const useCounter = (initialValue = 0) => {
// State to hold the value
const [count, setCount] = useState(initialValue);
// The function that set's the count based on the name of the element
function handleChange({ target }) {
const { name } = target;
setCount((prev) => (name === actionEnum.INCREMENT ? prev + 1 : prev - 1));
}
return {
count,
handleChange,
actionEnum
};
};
export default useCounter;
Counter.jsx
import useCounter from "./useCounter";
const Counter = () => {
const { count, handleChange, actionEnum } = useCounter();
return (
<>
<p>{count}</p>
<button name={actionEnum.INCREMENT} onClick={handleChange}>
+
</button>
<button name={actionEnum.DECREMENT} onClick={handleChange}>
-
</button>
</>
);
};
export default Counter;
Then finally just import the Counter component for each counter you need.
Example : https://codesandbox.io/s/patient-hooks-0ohyun?file=/src/App.js
You can also update the component so that it takes a prop for a fn that sets a global state which tracks all the counters
You should use 2 counters instead of just one, so you'll have 2 useState() statements.
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);
Then your buttons and displays need to reference the separate counter states appropriately.
<div className="counter">
<button className="increase-amount" onClick={increment}>+</button>
<input type="text" className="amount" defaultValue="0" value={count1}/>
<button className="decrease-amount" onClick={decrement}>-</button>
</div>
You'll also need to have 2 separate increment functions and 2 separate decrement functions. Alternately, you can have one increment function that takes an argument to specify which counter to update.

Redirecting to external link using ReactJS

I want to add button property which will redirect to external link when it is clicked. prop which should be added to button is siteURL .Button should be in class = "project-item-details-container". Do I have to install any external package?
sample button: Visit site
code which I have written -
const ProjectItem = props => {
const {projectDetails} = props
const {projectId, imageURL, description, title, siteURL} = projectDetails
return (
<>
<li className="project-item-container">
<img
className="project-item-image"
src={imageURL}
alt={`project-item${projectId}`}
/>
<div className="project-item-details-container">
<h1 className="project-item-title">{title}</h1>
<p className="project-item-description">{description}</p>
</div>
</li>
</>
)
}
const ProjectItem = props => {
const {projectDetails} = props
const {projectId, imageURL, description, title, siteURL} = projectDetails
return (
<>
<li className="project-item-container">
<img
className="project-item-image"
src={imageURL}
alt={`project-item${projectId}`}
/>
<div className="project-item-details-container">
<h1 className="project-item-title">{title}</h1>
<p className="project-item-description">{description}</p>
</div>
<a href={siteUrl}>{title}</a>
</li>
</>
)
}
you can do something like this
const ProjectItem = props => {
const {projectDetails} = props
const {projectId, imageURL, description, title, siteURL} = projectDetails
return (
<>
<li className="project-item-container">
<img
className="project-item-image"
src={imageURL}
alt={`project-item${projectId}`}
/>
<div className="project-item-details-container">
<h1 className="project-item-title">{title}</h1>
<p className="project-item-description">{description}</p>
<button onClick={()=>window.location.href=siteURL}>{title}</button>
</div>
</li>
</>
)
}
Well, I solved this.
I have used attribute in button element.
const ProjectItem = props => {
const {projectDetails} = props
const {projectId, imageURL, description, title, siteURL} = projectDetails
return (
<>
<li className="project-item-container">
<img
className="project-item-image"
src={imageURL}
alt={`project-item${projectId}`}
/>
<div className="project-item-details-container">
<h1 className="project-item-title">{title}</h1>
<p className="project-item-description">{description}</p>
<button type="button" className="project-redirect-button">
<a href={siteURL} alt="Broken Link">
Visit Site
</a>
</button>
</div>
</li>
</>
)
}

document.querySelector is not working in my react component

function Slider() {
const track=document.querySelector('.slide__track')//To access the div with class slide track
console.log(track);
return (
<div className="slider">
<i className="fas fa-chevron-left"></i>
<div className="head">
<h1 className="title">Based on your last search</h1>
<h6>View more</h6>
</div>
<div className="slider_container">
<ul className="slider__track">
<li className="slider__items">
<Card />
</li>
</ul>
</div>
<i className="fas fa-chevron-right"></i>
</div>
);
}
i cannot access the div with class slide__track.
What is the problem here?
Or how can i access that element?
Try and use this code in useEffect()
useEffect(() => {
const track = document.querySelector('.slide__track')
// have access to it
}, []);
I think it's because it is running before the DOM has been rendered. Move the track code into useEffect.
import {useEffect} from "react";
function Slider() {
useEffect(() => {
const track=document.querySelector('.slide__track')//To access the div with class slide track
console.log(track);
});
return (
<div className="slider">
<i className="fas fa-chevron-left"></i>
<div className="head">
<h1 className="title">Based on your last search</h1>
<h6>View more</h6>
</div>
<div className="slider_container">
<ul className="slider__track">
<li className="slider__items">
<Card />
</li>
</ul>
</div>
<i className="fas fa-chevron-right"></i>
</div>
);
}
You should be probably be using ref's to access dom elements inside react. see docs: https://reactjs.org/docs/refs-and-the-dom.html - reason being, if you have the below in a loop, or have multiple instances on the page, you'll need to be more careful with the selector approach.
import React, { useRef, useEffect } from 'react';
function Slider() {
const slideTrackRef = useRef(null);
useEffect(() => {
if (slideTrackRef && slideTrackRef.current) {
console.log(slideTrackRef.current);
}
}, [slideTrackRef]);
return (
<div className="slider">
<i className="fas fa-chevron-left" />
<div className="head">
<h1 className="title">Based on your last search</h1>
<h6>View more</h6>
</div>
<div className="slider_container">
<ul className="slider__track" ref={slideTrackRef}>
<li className="slider__items">
<p>tst</p>
</li>
</ul>
</div>
<i className="fas fa-chevron-right" />
</div>
);
}
export default Slider;

how to fetch api filter-data in ReactJS?

i have endpoint of filter data like this much-
localhost:8000/api/p_list?product_category=&color=&size=
whenever user filter the data the output would something look like this,
localhost:8000/api/p_list?product_category=1&color=1&size=2
the output of results comes according filter id as per user request to get. how to fetch the value whenever user request the id as per filter in reactjs?
i am probably new to reactjs. i am trying to solve this problem, it would be great if anybody could help me out what i am trying to do. thank you so much in advance.
my method how i tried to solve,
import React, {useEffect, useState} from "react";
import axios from 'axios';
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick(event) {
axios.get(`http://localhost:8000/api/p_list?product_category=${id}&color=${Id}&size=${Id}`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
}
return (
<div>
<div class="product_sidebar">
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Category <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{product_categoryData.map(product_categoryData => (
<p onClick={useEffect}>{product_categoryData.category_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Color <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_colorData.map(filter_colorData => (
<p onClick={useEffect}>{filter_colorData.color_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Size <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_sizeData.map(filter_sizeData => (
<p onClick={useEffect}>{filter_sizeData.size_title}</p>
))}
</div>
</div>
</div>
</div>
</div>
);
};
export default PostListPageByUser;
try storing the values of category size and color in state and make the api call in a useEffect hook that will run every-time the state of one of these values changes.
in generel:
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [category, setCategory] = useState('');
const [color, setColor] = useState('');
const [size, setSize] = useState('');
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
useEffect(() => { axios.get(`http://localhost:8000/api/p_list?product_category=${category}&color=${color}&size=${size}`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
})}, [size,color,category])
and in your form modify mutate the state
import React, {useEffect, useState} from "react";
import axios from 'axios';
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
const [productCategory, setProductCategory] = useState(null);
const [productColor, setProductColor] = useState(null);
const [productSize, setProductSize] = useState(null);
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick() {
axios.get(`http://localhost:8000/api/p_list?product_category=${productCategory}&color=${productColor}&size=${productSize}`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
}
useEffect(
() => {
handleClick();
},
[productCategory,productColor,productSize],
);
return (
<div>
<div class="product_sidebar">
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Category <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{product_categoryData.map(product_categoryData => (
<p onClick={setProductCategory(product_categoryData.category_title)}>{product_categoryData.category_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Color <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_colorData.map(filter_colorData => (
<p onClick={setProductColor(filter_colorData.color_title)}>{filter_colorData.color_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Size <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_sizeData.map(filter_sizeData => (
<p onClick={setProductSize(filter_sizeData.size_title)}>{filter_sizeData.size_title}</p>
))}
</div>
</div>
</div>
</div>
</div>
);
};
Below step should happen :-
Onclick set state
2.state change call API
There are several reasons why your onClick prop is not firing when it's changed.
You are calling useEffect directly in your onClick even though you didn't define it in your code.
You are not using useState to set category, colour or size anywhere in your code to use it to make async calls.
import React, { useEffect, useState } from "react";
import axios from "axios";
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
const [categoryTitle, setCategoryTitle] = useState("");
const [color, setColor] = useState("");
const [size, setSize] = useState("");
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
async function handleClick(event) {
try {
const response = await axios.get(
`http://localhost:8000/api/p_list?product_category=${categoryTitle}&color=${color}&size=${size}`,
{
cancelToken: signal.token,
}
);
setPost(response.data);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
this.handleClick();
}, [categoryTitle, color, size]);
return (
<div>
<div class="product_sidebar">
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">
Category <i class="right fas fa-caret-down"></i>{" "}
</div>
<div class="select_option_dropdown">
{product_categoryData.map((product_categoryData) => (
<p
onClick={setCategoryTitle(
product_categoryData.category_title
)}
>
{product_categoryData.category_title}
</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">
Color <i class="right fas fa-caret-down"></i>{" "}
</div>
<div class="select_option_dropdown">
{filter_colorData.map((filter_colorData) => (
<p onClick={setColor(filter_colorData.color_title)}>
{filter_colorData.color_title}
</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">
Size <i class="right fas fa-caret-down"></i>{" "}
</div>
<div class="select_option_dropdown">
{filter_sizeData.map((filter_sizeData) => (
<p onClick={setSize(filter_sizeData.size_title)}>
{filter_sizeData.size_title}
</p>
))}
</div>
</div>
</div>
</div>
</div>
);
}
export default PostListPageByUser;

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

Categories

Resources