How can I increment/decrement separate counters in React? - javascript

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.

Related

How can i setState for color change

I already have the condition, but i need to set the state, if i setColor on the if method, give me error- Too many re-renders. React limits the number of renders to prevent an infinite loop.
State:
const [color, setColor] = useState();
Map:
{data.map((doc) => {
let verificacao = "";
if (doc.status === "Não Necessário") {
verificacao = "Proxima Verificação:";
setColor(true)
} else if (doc.status === "Verificado e Conforme") {
verificacao = "Data:";
setColor(false)
} else {
console.log("ERRO");
}
return (
The span i want to change the color:
<div className="row">
<div className="pontos">
<span className={color ? "red" : "green"}>
{doc.status}
</span>
<span className="data-status">{verificacao}</span>
{JSON.stringify(
doc.dateVerificado
.toDate()
.toISOString()
.replace(/T.*/, "")
.split("-")
.reverse()
.join("-")
)}
</div>
</div>
Full Code:
import React, { useEffect, useState } from "react";
import { Button } from "react-bootstrap";
import ManutencaoDataService from
"../../Services/ManutecaoDataService";
import "./ManutencaoInfo.css";
const ManutencaoInfo = ({ getDataId }) => {
const [data, setData] = useState([]);
const [color, setColor] = useState();
useEffect(() => {
getData();
return () => {
setData([]);
};
}, []);
const getData = async () => {
const data = await ManutencaoDataService.getAllData();
console.log(data.docs);
setData(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
const deleteHandler = async (id) => {
await ManutencaoDataService.deleteData(id);
getData();
};
return (
<>
<div className=" container mb-2">
<Button variant="dark edit" onClick={getData}>
Atualizar Lista
</Button>
</div>
{/* <pre>{JSON.stringify(books, undefined, 2)}</pre>} */}
{data.map((doc) => {
let verificacao = "";
if (doc.status === "Não Necessário") {
verificacao = "Proxima Verificação:";
setColor(true)
} else if (doc.status === "Verificado e Conforme") {
verificacao = "Data:";
setColor(false)
} else {
console.log("ERRO");
}
return (
<div key={doc.id} className="container-principal">
<div className="container">
<div className="row relatorio">
<div className="col">
<div className="departamento">
<h3>{doc.departamentos}</h3>
</div>
</div>
</div>
<div className="row detalhes">
<div className="col">
<div className="row">
<div className="pontos">
<span className="identificacao">Equipamento:
</span>
{doc.equipamentos}
</div>
</div>
<div className="row">
<div className="pontos">
<span className="identificacao">Responsável:
</span>
{doc.responsaveis}
</div>
</div>
<div className="row">
<div className="pontos">
<span className="codigo">{doc.codigos.codigo}
</span>
<span className="tipo">{doc.tipo}</span>
</div>
</div>
</div>
<div className="col ">
<div className="row">
<div className="pontos">
<span className="identificacao">Data Manutenção:
</span>
{JSON.stringify(
doc.dateManutencao
.toDate()
.toISOString()
.replace(/T.*/, "")
.split("-")
.reverse()
.join("-")
)}
</div>
</div>
<div className="row">
<div className="pontos">
<span className={color ? "red" : "green"}>
{doc.status}
</span>
<span className="data-status">{verificacao}</span>
{JSON.stringify(
doc.dateVerificado
.toDate()
.toISOString()
.replace(/T.*/, "")
.split("-")
.reverse()
.join("-")
)}
</div>
</div>
<div className="row">
<div className="pontos">{doc.codigos.observacoes}
</div>
</div>
</div>
</div>
<div className="row botoes">
<div className="col">
<span className="botao-editar">
<Button
variant="secondary"
className="edit"
onClick={(e) => getDataId(doc.id)}
>
Editar
</Button>
</span>
<span className="botao-apagar">
<Button
variant="danger"
className="delete"
onClick={(e) => deleteHandler(doc.id)}
>
Apagar
</Button>
</span>
</div>
</div>
</div>
</div>
);
})}
</>
);
};
export default ManutencaoInfo;
Instead of using state, I would recommend using doc's status property for using the correct CSS class like this:
<span className={doc.status === "Não Necessário" ? "red" : "green"}>
{doc.status}
</span>
import React, { useEffect, useState } from "react";
import { Button } from "react-bootstrap";
import ManutencaoDataService from
"../../Services/ManutecaoDataService";
import "./ManutencaoInfo.css";
import classNames from 'classnames';
const ManutencaoInfo = ({ getDataId }) => {
const [data, setData] = useState([]);
useEffect(() => {
getData();
}, []);
const getData = async () => {
const data = await ManutencaoDataService.getAllData();
console.log(data.docs);
setData(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
}
return (
<>
...
{data.map((doc) => {
return (
<div key={doc.id} className="container-principal">
<div className="container">
...
<div className="row detalhes">
...
<div className="col ">
...
<div className="row">
<div className="pontos">
<span className={classNames({red: doc.status === "Não Necessário", green:doc.status === "Verificado e Conforme" })}>
{doc.status}
</span>
<span className="data-status">{
doc.status === "Não Necessário" ? "Proxima Verificação:" : doc.status === "Verificado e Conforme" ? "Data:" :""
}</span>
....
</div>
</div>
....
</div>
</div>
...
</div>
</div>
);
})}
</>
);
};
export default ManutencaoInfo;
create a new component which renders inside the map function, it will be better to maintain
I think you are overcomplicating it with introducing state variable.
You can just use local variable in your function like this:
// Remove this state
// const [color, setColor] = useState();
{data.map((doc) => {
let verificacao = "";
let color; // add this var
if (doc.status === "Não Necessário") {
verificacao = "Proxima Verificação:";
color = 'red' // changed
} else if (doc.status === "Verificado e Conforme") {
verificacao = "Data:";
color = 'green' // changed
} else {
console.log("ERRO");
}
return (
// ...
<span className={color}> {/* changed */}
{doc.status}
</span>
// ...
)

Filtering Data to load a particular response on click

Currently I have a component that is loaded when I call my API. This content has a CitizenshipType field that separates the items from each other. I have 2 buttons on top which I want to use to filter my data. 1 button is called Europe which should bring out all the content where CitizenshipType=Europe, etc. Currently I have all my data showing without any filtering. Here is my code:
Citizenship Page:
export default function Citizenship({ items, citi }) {
return (
<>
<div>
<div onClick=//SomeFunction>
CARRIBEAN
</div>
<div onClick=//SomeFunction>
EUROPE
</div>
</div>
<div>
<div onClick=//SomeFunction>
OTHER PROGRAMS
</div>
</div>
<div>
{items &&
items.map((item) => (
<div style={{ padding: "40px" }}>
<div class="citizen-item" key={item.id}>
<div className="container6">
<img
src={`http://localhost:1337${item.Thumbnail.url}`}
/>
<div>
{item.Title}
</div>
<div>
Access to {item.CountriesAccessible} countries
</div>
<div>
<button class="findButton">FIND OUT MORE</button>
</div>
</div>
</div>
</div>
))}
{citi &&
citi.map((test) => (
<div style={{ padding: "40px" }}>
<div class="citizen-item" key={test.id}>
<div className="container6">
<img
src={`http://localhost:1337${test.Thumbnail.url}`}
/>
<div>
{test.Title}
</div>
<div>
Access to {test.CountriesAccessible} countries
</div>
<div>
<button class="findButton">FIND OUT MORE</button>
</div>
</div>
</div>
</div>
))}
</>
);
}
Home Page where I am calling the APIs:
export default function Home({ items, citi }) {
return (
<div>
<Benefits />
<Citizenship items={items} citi={citi} />
<Video />
</div>
);
}
export async function getStaticProps() {
const CitizenshipEUres = await fetch(
"http://localhost:1337/citizenships?_limit=5&CitizenshipType=Europe"
);
const CitizenshipCAres = await fetch(
"http://localhost:1337/citizenships?_limit=5&CitizenshipType=Caribbien"
);
const items = await CitizenshipEUres.json();
const citi = await CitizenshipCAres.json();
return {
props: { items, citi },
};
}
you toggle them with states:
import React, { useState } from 'react'
export const TestComponent = () => {
const [carribeanIsShowing, setShowCarribean] = useState(false)
const [europeIsShowing, setShowEurope] = useState(false)
const toggleCarribean = () => {
if (!carribeanIsShowing) {
if(europeIsShowing) {
setShowEurope(false)
}
setShowCarribean(!carribeanIsShowing)
} else {
return
}
}
const toggleEurope = () => {
if (!europeIsShowing) {
if(carribeanIsShowing) {
setShowCarribean(false)
}
setShowEurope(!europeIsShowing)
} else {
return
}
}
return (
<div>
<button onClick={() => toggleCarribean()}>
CARRIBEAN
</button>
<button onClick={() => toggleEurope()}>
EUROPE
</button>
{europeIsShowing && <div>Europe</div>}
{carribeanIsShowing && <div>carribean</div>}
</div>
)
}
Create a new variable where you store the current CitizenshipType, with a default value of 'Europe'.
const [currentCitizenshipType, setCurrentCitizenshipType] = useState(
"Europe"
);
You change your onClick event
<div onClick={() => setCurrentCitizenshipType('Europe')}>
EUROPE
</div>
And finally add a filter statment to your items.map call:
{
items
.filter((item) => item.citizenshipType === currentCitizenshipType)
.map((item)
...}

Modal dialog displays from all elements of mapped array. How to select each item by ts and react js?

This code:
How to display a dialog when a button is clicked using react and typescript?
I wanna open dialog from each todos, how to make it ? I used react js and typescript. Help me to resolve this problem.
interface ListProps {
todos: INote[];
onDelete: (title: string) => void;
}
const TodoList: React.FunctionComponent<ListProps> = ({ todos, onDelete }) => {
const [showAlert, setShowAlert] = useState(false);
const [todo, setTodos] = useState(null);
How to select each item by ts?It doesn't work. What is reason? Thanks!
const handleOpenDialog = (todos: any) => {
setTodos(todos);
setShowAlert(true);
};
const handleCloseDialog = () => {
setShowAlert(false);
};
return (
<>
<section className="list list--wrapper">
{todos.map((todos) => (
<div className="item list__item" key={todos.title}>
<span className="item__title">{todos.title}</span>
<div className="item__group">
<input
className="item__completed"
type="checkbox"
checked={todos.completed}
/>
<span className="item__decs">{todos.desc}</span>
</div>
<div className="item__btn">
<button
className="item__btnd"
onClick={() => handleOpenDialog(todos)}
>
Delete
</button>
<button className="item__btne">Edit</button>
</div>
{showAlert && todo && (
<AlertDialog
handleCloseDialog={handleCloseDialog}
title={todos.title}
/>
)}
</div>
))}
</section>
</>
);
};
export default TodoList;
just add a condition to only show the AlertDialog on selected todos
<section className="list list--wrapper">
{todos.map((todos) => (
<div className="item list__item" key={todos.title}>
<span className="item__title">{todos.title}</span>
<div className="item__group">
<input
className="item__completed"
type="checkbox"
checked={todos.completed}
/>
<span className="item__decs">{todos.desc}</span>
</div>
<div className="item__btn">
<button
className="item__btnd"
onClick={() => handleOpenDialog(todos)}
>
Delete
</button>
<button className="item__btne">Edit</button>
</div>
{showAlert && todos.title===todo?.title && (
<AlertDialog
handleCloseDialog={handleCloseDialog}
title={todos.title}
/>
)}
</div>
))}
</section>
or just move the AlertDialog outside the map
<section className="list list--wrapper">
{todos.map((todos) => (
<div className="item list__item" key={todos.title}>
<span className="item__title">{todos.title}</span>
<div className="item__group">
<input
className="item__completed"
type="checkbox"
checked={todos.completed}
/>
<span className="item__decs">{todos.desc}</span>
</div>
<div className="item__btn">
<button
className="item__btnd"
onClick={() => handleOpenDialog(todos)}
>
Delete
</button>
<button className="item__btne">Edit</button>
</div>
</div>
))}
{showAlert && todo && (
<AlertDialog
handleCloseDialog={handleCloseDialog}
title={todos.title}
/>
)}
</section>

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

onClick doesn't fire at all times

I started playing with some React/Redux + t7 (in order to avoid any sort of transpiling), for the sake of learning.
When it all started making some sense to me, I encountered this voodooish issue, where the bounded onClick function sometimes fires and sometimes doesn't (?!)
As you can see, clicking the plus button doesn't always invoke the bounded function to onClick.
I'm using the latest version of Google Chrome (v53).
What the hell?
JS
'use strict';
const store = Redux.createStore(Redux.combineReducers({
todos: (state = [], action) => {
switch(action.type) {
case 'ADD_TODO':
return state.concat([action.payload]);
default:
return [];
}
}
}));
t7.module((t7) => {
t7.assign("AddTodo", React.createClass({
addTodo() {
console.log('clicked');
return store.dispatch({
type: 'ADD_TODO',
payload: {
text: this.refs.todoText.value,
}
})
},
render() {
return t7`
<div className="row">
<div className="col-xs-4 form-group-lg">
<input className="form-control" ref="todoText"/>
</div>
<div className="col-xs-2">
<button className="btn btn-lg btn-info">
<span className="glyphicon glyphicon-plus"
onClick="${this.addTodo}"
style=${{fontSize: 'large'}}>
</span>
</button>
</div>
</div>
`;
}
}));
t7.assign("TodoList", React.createClass({
render() {
return t7`
<div className="row">
<div className="col-xs-12">
<ul>
${store.getState().todos.map((todo, i) => t7`
<li key=${i}>${todo.text}</li>
`)}
</ul>
</div>
<div>
`;
}
}));
const render = () => ReactDOM.render(
t7`
<div className="container">
<div className="jumbotron">
<h1>Todos</h1>
</div>
<AddTodo />
<TodoList />
</div>
`, document.getElementById('root')
);
store.subscribe(render);
render();
});
Your Click event works whenver your click on the glyphicon plus and not outside it. The issue is that you have placed the onClick event at the wrong place add it to the button rather than the span and it will work
render() {
return t7`
<div className="row">
<div className="col-xs-4 form-group-lg">
<input className="form-control" ref="todoText"/>
</div>
<div className="col-xs-2">
<button className="btn btn-lg btn-info" onClick="${this.addTodo}">
<span className="glyphicon glyphicon-plus"
style=${{fontSize: 'large'}}>
</span>
</button>
</div>
</div>
`;
}

Categories

Resources