I am trying to render an array of counters using the counter component dynamically however they get rendered horizontally and I need them rendered vertically.
I am following the react tutorial from codewithmosh.com.
I have followed all the instructions and gone over the code countless times. I would also like to note that the instructor is using and older version of react and bootstrap
counter.jsx
import React, { Component } from "react";
class Counter extends Component {
state = {
count: this.props.value
};
handleIncriment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<React.Fragment>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button
onClick={this.handleIncriment}
className="btn btn-secondary btn-sm"
>
Incriment
</button>
</React.Fragment>
);
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.count === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { count } = this.state;
return count === 0 ? "zero" : count;
}
}
export default Counter;
Counters.jsx
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
render() {
return (
<div>
{this.state.counters.map(counter => (
<Counter key={counter.id} value={counter.value} selected={true} />
))}
</div>
);
}
}
export default Counters;
If you use a div instead of a Fragment inside Counter, your counters will be block elements, and will render vertically.
Related
I'm trying to change the appearance of a button based on if that element exists in state. It is a multiple selection selection. So setAnswer is called, which calls addAnswer. I then want to set the className based on whether the element is in state but I'm just not getting it.
{question.values.map(answer => {
return <button className="buttons" key={answer} onClick={() => addAnswer(answer)}>
{answer}</button>
})}
const addAnswer = (answer) => {
let indexAnswer = answers.indexOf(answer)
if (indexAnswer > -1) {
setAnswer((answers) => answers.filter((a) => {
return a != answer }))}
else setAnswer([...answers, answer])
};
You can conditionally set a class like this
{question.values.map(answer => {
return (<button
className={answers.indexOf(answer) === -1 ? 'class1' : 'class2'}
key={answer}
onClick={() => addAnswer(answer)}
>
{answer}
</button> );
})}
clsx is the perfect candidate for this. You can conditionaly set one or more classNames which get used if a condition is true.
Here's a real working snippet I made which is also available here https://codesandbox.io/s/gracious-sound-2d5fr?file=/src/App.js
import React from "react";
import "./styles.css";
import clsx from "clsx";
import { createUseStyles } from "react-jss";
// Create your Styles. Remember, since React-JSS uses the default preset,
// most plugins are available without further configuration needed.
const useStyles = createUseStyles({
answer1: { color: "red" },
answer2: { color: "green" },
answer3: { color: "yellow" }
});
export default function App() {
const classes = useStyles();
const questions = {
values: [
{ type: 1, value: "aaaa" },
{ type: 2, value: "bbbb" },
{ type: 3, value: "cccc" },
{ type: 1, value: "dddd" },
{ type: 2, value: "eeee" },
{ type: 3, value: "ffff" }
]
};
return (
<div className="App">
{questions.values.map(answer => (
<p>
<button
className={clsx(classes.always, {
[classes.answer1]: answer.type === 1,
[classes.answer2]: answer.type === 2,
[classes.answer3]: answer.type === 3
})}
>
{answer.value}
</button>
</p>
))}
</div>
);
}
for more information on clsx see this example here Understanding usage of clsx in React
Alternatively you can determine the class name via logic and set it in a variable like this
const getClassName = ()=> {
switch(answer) {
case(1): return "class1"
case(2): return "class2"
...
}
}
render(
/// within the map function
< className={getClassName()} />
)
It's my first day learning react and I'm stuck with an issue (I'm following Mosh's tutorial):
import React, { Component } from "react";
class Counter extends Component {
state = {
value: this.props.value,
};
handleIncrement = () => {
console.log("Click!");
this.setState({ value: this.state.value + 1 });
};
handleDecrement = () => {
console.log("Click!");
if (this.state.value !== 0) {
this.setState({ value: this.state.value - 1 });
}
};
render() {
return (
<div className="row align-items-center">
<div className="col">
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
</div>
<div className="col">
<button
onClick={() => this.handleIncrement({ id: 1 })}
className="btn btn-dark"
>
+
</button>
<button
onClick={() => this.handleDecrement({ id: 1 })}
className={this.isLessThanZero()}
>
-
</button>
</div>
<div className="col">
<button
onClick={() => this.props.onDelete(this.props.id)}
className="btn btn-danger m-2"
>
Delete
</button>
</div>
</div>
);
}
isLessThanZero() {
let classes = "btn btn-dark ";
classes += this.state.value === 0 ? "disabled" : "";
return classes;
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.value === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
let { value } = this.state;
return value === 0 ? <h1>Zero</h1> : value;
}
}
export default Counter;
This is a counter component that just responds to the buttons. I'm including those in another component:
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
],
};
handleDelete = (counterId) => {
console.log("Event detected! Delete", counterId);
};
render() {
return (
<div className="cont">
{this.state.counters.map((counter) => (
<Counter
value={counter.value}
key={counter.id}
onDelete={this.handleDelete}
></Counter>
))}
</div>
);
}
}
export default Counters;
In the handleDelete function, when called, I'm getting undefined for the counterId. When I check in the ReactComponents Chrome extention, I see that there isn't any ID:
Why is this happening?
The problem is you are not passing the counter for this.handleDelete. You need to explicitly pass it.
<Counter
value={counter.value}
key={counter.id}
onDelete={() => this.handleDelete(counter.id)}
/>
In the above snippet, I am passing a new function to the Counter component, the function just calls this.handleDelete with the counter.id of the corresponding component.
I am trying to send two variables from the Component 'Game' to the Component 'App' but I am unsure how to send more than one prop at a time.
This what I have:
//App Component
class App extends Component {
constructor(props) {
super(props)
this.state = {
score: 0,
}
this.changeScore = this.changeScore.bind(this)
}
changeScore(newScore) {
this.setState(prevState => ({
score: prevState.score + newScore
}))
}
render() {
return(
<div>
<Game onClick={this.changeScore}/>
<Score score={this.state.score}/>
</div>
)
}
}
//Game Componenet
class Game extends Component {
constructor(props) {
super(props)
this.state = {
score: 0,
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
console.log('Clicked')
this.props.onClick(this.state.score)
}
render() {
return(
<div>
<button onClick={this.handleClick}> Score Button </button>
</div>
)
}
}
//Score Component
class Score extends Component {
render() {
const score = this.props.score
return(
<div>
<h1>Score: {score}</h1>
</div>
)
}
}
With this I am able to send the prop 'score' from 'Game' to 'App' but I was wondering if it was possible to send more then just the one prop, such as 'score' and a new variable, 'count' with the same button press, to ultimately be able to display both 'score' and 'count' in the 'Score' Componenet.
Thanks.
Sure you can, just update the function you defined in the Parent App component to accept two arguments.
App.js
class App extends Component {
constructor(props) {
super(props)
this.state = {
score: 0,
count: 0
}
this.changeScore = this.changeScore.bind(this)
}
changeScore(newScore, count) {
this.setState(prevState => ({
score: prevState.score + newScore,
count: prevState.count + count
}))
}
render() {
return(
<div>
<Game
onClick={this.changeScore}
score={this.state.score}
count={this.state.count}
/>
<Score score={this.state.score} count={this.state.count}/>
</div>
)
}
}
Game.js //refactored since it doesnt need to use state
const Game = ({ onClick, count, score }) => {
const newScore = score + 10
const newCount = count + 1
return (
<button onClick={() => onClick(newScore, newCount)}>Score</button>
)
}
You can definitely send more than one prop at a time. Here's the example that you've described:
<Score
score={this.state.score}
count={this.state.count}
/>
And in your Score component:
class Score extends Component {
render() {
const score = this.props.score;
const count = this.props.count;
return(
<div>
<h1>Score: {score}</h1>
<h1>Count: {count}</h1>
</div>
)
}
}
I was following Mosh Hamedani's tutorial here for creating react-app.
I did exactly what he said.
I'm trying to pass an argument called product to a function which is called for onClick
However, I'm getting an error for which I didn't find much info.
Here's the code:
import React, { Component } from "react";
class Counter extends Component {
state = {
count: 0
};
formatCount() {
return this.state.count === 0 ? "Zero" : this.state.count;
}
handleIncrement = product => {
console.log(product);
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<React.Fragment>
<span className={this.formatSpan()}>{this.formatCount()}</span>
<button
onClick={() => this.handleIncrement(product)}
className="btn btn-primary"
>
Increment
</button>
</React.Fragment>
);
}
}
export default Counter;
Here's the error:
Failed to compile.
./src/components/counter.jsx Line 41: 'product' is not defined
no-undef
Search for the keywords to learn more about each error.
This happened to you because you did not give an input to your function. product is your input variable not input value. If for example ran a code like below, and check your browser console you see that it prints value of 1.
import React, { Component } from "react";
class Counter extends Component {
state = {
count: 0
};
formatCount() {
return this.state.count === 0 ? "Zero" : this.state.count;
}
handleIncrement = product => {
console.log(product);
this.setState({ count: this.state.count + 1 });
};
render() {
const product=1;
return (
<React.Fragment>
<span className={this.formatSpan()}>{this.formatCount()}</span>
<button
onClick={() => this.handleIncrement(product)}
className="btn btn-primary"
>
Increment
</button>
</React.Fragment>
);
}
}
export default Counter;
I hope it was helpful. Please vote me up if it worked for you:)
New to react and I am removing the local state in my counter component and will be relying on the props to receive the data that it needs. I believe this is called a controlled component. After I got rid of the state and changed every where I was using this.state to this.props, I am no longer able to see the box that displays the value when I click my increment button. I will post all the code down below.
/* Counter Component*/
import React, { Component } from "react";
class Counter extends Component {
renderTags() {
return (
<ul>
{this.state.tags.length === 0 && <p> There are no tags </p>}
{this.state.tags.map(tag => (
<li key={tag}> {tag} </li>
))}
</ul>
);
}
// You can do styles this way or do it inline
// styles = {
// fontSize: 50,
// fontWeight: "bold"
// };
render() {
return (
<div>
<span style={{ fontSize: 20 }} className={this.getBadgeClasses()}>
{this.formatCount()}
</span>
<button
onClick={() => this.props.onIncrement(this.props.counter)}
className="btn btn-secondary btn-sm"
>
Increment
</button>
<button
onClick={() => this.props.onDelete(this.props.counter.id)}
className="btn btn-danger btn-sm m-2"
>
Delete
</button>
{/* {this.renderTags()}
<p>{this.state.tags.length === 0 && "Please create a new tag"}</p> */}
</div>
);
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.props.counter.value === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { count } = this.props.counter;
return count === 0 ? "Zero" : count;
}
}
export default Counter;
/* Counters Component */
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 5 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleIncrement = counter => {
console.log(counter);
};
handleReset = () => {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters });
};
handleDelete = counterID => {
const counters = this.state.counters.filter(c => c.id !==
counterID);
this.setState({ counters });
};
render() {
return (
<React.Fragment>
<button onClick={this.handleReset} className="btn btn-dark btn-sm m-2">
Reset
</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.handleDelete}
counter={counter}
onIncrement={this.handleIncrement}
/>
))}
</React.Fragment>
);
}
}
export default Counters;
You can't see the values since you are using a wrong key for your counter.
formatCount() {
const { count } = this.props.counter;
return count === 0 ? "Zero" : count;
}
There isn't any key named count in your counter. It is value. So, you should use it or you need to destruct it like this:
const { value: count } = this.props.counter
But, using the same name is more consistent I think. Also, your Counter component would be a stateless one since you don't need any state or lifecycle method there.
One extra change would be done to the handler methods like onClick for onIncrement. If you use an arrow function, that function will be recreated in every render. You can use an extra handler method. Here is the complete working example (simplified for a clear view).
class Counters extends React.Component {
state = {
counters: [
{ id: 1, value: 5 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleIncrement = counter => {
const { counters } = this.state;
const newCounters = counters.map( el => {
if( el.id !== counter.id ) { return el; }
return { ...counter, value: counter.value + 1 }
} )
this.setState({ counters: newCounters});
};
handleReset = () => {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters });
};
handleDelete = counter => {
const { id: counterID } = counter;
const counters = this.state.counters.filter(c => c.id !== counterID);
this.setState({ counters });
};
render() {
return (
<div>
<button onClick={this.handleReset} className="btn btn-dark btn-sm m-2">
Reset
</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.handleDelete}
counter={counter}
onIncrement={this.handleIncrement}
/>
))}
</div>
);
}
}
const Counter = props => {
const { counter, onIncrement, onDelete} = props;
function formatCount(){
const { value } = counter;
return value === 0 ? "Zero" : value;
}
function handleIncrement(){
onIncrement( counter );
}
function handleDelete(){
onDelete( counter );
}
return (
<div>
<span>
{formatCount()}
</span>
<button
onClick={handleIncrement}
>
Increment
</button>
<button
onClick={handleDelete}
>
Delete
</button>
</div>
);
}
ReactDOM.render(<Counters />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>