Show hide multiple elements with react - reactjs

I want to use the same function showHide to show/hide each element within the parent.
When I press the button all 3 blocks reacts and hide or show.
How can I extend the function to work individualy for each div?
This is a localhost test project so I can't provide any link unfortunately.
Here you can see the final result
import React, { Component } from 'react';
class Homepage extends Component {
constructor( props ){
super( props )
this.state = {show : true};
this.showHide = this.showHide.bind(this)
}
render() {
return (
<section id="content">
<div className="top-content">
<div className="container">
<h1>React</h1>
<h2>A JavaScript library for building user interfaces</h2>
</div>
</div>
<div className="container">
<div>
<div>
<h3>Declarative</h3>
<button onClick={this.showHide} className="button-primary btn">{this.changeName()}</button>
{ this.state.show &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Component-Based</h3>
<button onClick={this.showHide} className="button-primary btn">{this.changeName()}</button>
{ this.state.show &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Learn Once, Write Anywhere</h3>
<button onClick={this.showHide} className="button-primary btn">{this.changeName()}</button>
{ this.state.show &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
</div>
</div>
</section>
);
}
changeName(){
let text = "text "
text += this.state.show === true ? "hide" : "show";
return text;
}
showHide(){
const { show } = this.state;
this.setState( { show : !show})
}
}
export default Homepage;

The problem here is that your using the same state variable for each div (this.state.show).
If you want to have the divs behave differently, they each need their own state.
import React, { Component } from 'react';
class Homepage extends Component {
constructor( props ){
super( props )
this.state = {show: [true, true,true]};
}
render() {
return (
<section id="content">
<div className="top-content">
<div className="container">
<h1>React</h1>
<h2>A JavaScript library for building user interfaces</h2>
</div>
</div>
<div className="container">
<div>
<div>
<h3>Declarative</h3>
<button onClick={()->this.showHide(0)} className="button-primary btn">{this.changeName()}</button>
{ this.state.show[0] &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Component-Based</h3>
<button onClick={()->this.showHide(1)} className="button-primary btn">{this.changeName()}</button>
{ this.state.show[1] &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Learn Once, Write Anywhere</h3>
<button onClick={()->this.showHide(2)} className="button-primary btn">{this.changeName()}</button>
{ this.state.show[2] &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
</div>
</div>
</section>
);
}
changeName(){
let text = "text "
text += this.state.show === true ? "hide" : "show";
return text;
}
showHide(num){
this.setState((prevState) => {
const newItems = [...prevState.show];
newItems[num] = !newItems[num];
return {show: newItems};
});
}
}
export default Homepage;
Obviously there are nicer ways of doing this, but this is just an example to show the separation of states.
Can't test it right now, but shouldn't be far off.
UPDATE: #Lasitha ty for the much nicer edit!

Related

React) How to return to the main page

The toBack() function worked well in the local environment, but the page cannot be found after deployment to netlify.
How should I write the code?
class Itemdetail extends Component {
toBack = () => {
window.location.replace("/main");
};
render() {
const { name, description, qr_link } = this.props.item;
return (
<div className={styles.item_box}>
<div className={styles.item_box_inner}>
<div className={styles.qr_box}>
<img src={qr_link} alt="qr_link" />
</div>
<div className={styles.text_box}>
<p className={styles.name}>{name}</p>
<p className={styles.description}>{description}</p>
<div onClick={this.toBack} className={styles.back_btn}>
Go back
</div>
</div>
</div>
</div>
);
}
}

How to add different events with this Class |REACT JS|

I wrote down the code below.
My outcome should be 4 buttons that increment and decrement a value.
Is working but all buttons change at the same time!
The outcome I would like to get button by button and not at the same time.
I've already tried with an Array but seems I'm not on the right way!
import React from 'react';
class Counter extends React.Component {
constructor() {
super();
this.state = {
cnt: 0
};
}
handleDecrement = () => {
this.setState({
cnt: this.state.cnt + 1
});
}
handleIncrement = () => {
this.setState({
cnt: this.state.cnt - 1
});
}
render() {
return (
<><div className = "btn"></div>
<header>
<h1>Tarantino Shop</h1>
</header>
<div>
<img src= "images/walltara.png" alt="cart" width = "80%"/>
</div>
<div className="divprimario">
<div className="items">
<img src= "images/tara1.jpg" alt="cart" />
<div className = "titles"> T-Shirt Pulp Fiction</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
<div className="items">
<img src= "images/tara2.jpg" alt="cart" />
<div className = "titles">T-Shirt Tarantino </div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
<div className="items">
<img src= "images/tara3.jpg" alt="cart" />
<div className = "titles">T-Shirt Le Iene</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
<div className="items">
<img src= "images/tara4.jpg" alt="cart" />
<div className = "titles">T-Shirt Random</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
</div>
</>
);
}
}
export default Counter;
So, why all the buttons change at the same time? What am I'm doing wrong?
you are only using one variable cnt to keep track of the count. If you want them to update separately, each button must increment or decrement a different state variable.
For example you could use pulpFictionCnt, tarantinoCnt etc to keep track of the different counts.
Keep a separate component for your Counter and provide other data as props.
import React from "react";
class Counter extends React.Component {
constructor() {
super();
this.state = {
cnt: 0
};
}
handleDecrement = () => {
this.setState({
cnt: this.state.cnt + 1
});
};
handleIncrement = () => {
this.setState({
cnt: this.state.cnt - 1
});
};
render() {
return (
<>
<div className="divprimario">
<div className="items">
<img src="images/tara1.jpg" alt="cart" />
<div className="titles">{this.props.title}</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
</div>
</>
);
}
}
export default Counter;
Following may be some other component,
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import Counter from "./Counter";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<div>
<div className="btn"></div>
<header>
<h1>Tarantino Shop</h1>
</header>
<div>
<img src="images/walltara.png" alt="cart" width="80%" />
</div>
<Counter title={"T-Shirt Pulp Fiction"} />
<Counter title={"T-Shirt Tarantino"} />
<Counter title={"T-Shirt Le Iene"} />
<Counter title={"T-Shirt Random"} />
</div>
</StrictMode>,
rootElement
);
Sandbox code here => https://codesandbox.io/s/laughing-bhabha-zsyvw?file=/src/Counter.js

REACT : empty render despite no errors

I am using the Context API to manage state in a small app. I get the response OK, the Consumer has it, so I map through it and want to pass down data from it to a Product Card component through props. And the Product Card renders absolutely nothing. I get no errors whatsoever. Can anyone help me out please? Here is the code of parent component:
import Pagination from "./Pagination";
import { Consumer } from "../context";
export default class Browse extends Component {
render() {
return (
<Consumer>
{value => {
const { search } = value;
return (
<ProductsGrid>
{search.map(beer => (
<ProductCard
key={beer.id}
beerId={beer.id}
beerName={beer.name}
beerTagline={beer.tagline}
beerAbv={beer.abv}
firstBrewed={beer.first_brewed}
imageUrl={beer.image_url}
/>
))}
</ProductsGrid>
);
}}
</Consumer>
);
}
}`````
and here is the Product Card component:
```export default class ProductCard extends React.Component {
render() {
return (
<div className="product-card">
<div className="product-card-inner">
<div className="product-info-container">
<h1 className="beer-name">{this.props.beerName}</h1>
<p className="beer-type">{this.props.beerTagline}</p>
<p className="beer-alcohol">{this.props.beerAbv}%</p>
<p className="first-brewed">
First brewed: {this.props.firstBrewed}
</p>
</div>
<div className="beer-image-container">
<img src={this.props.imageUrl} alt="beer" />
</div>
<div className="price-container">
<h1>£ 3.50</h1>
</div>
<div className="button-container">
<div className="quantity-container">
<p className="minus-sign"> - </p>
<p className="qty-number"> 0 </p>
<p className="plus-sign"> + </p>
</div>
<div className="add-container">
<IoIosCart />
<p>Add</p>
</div>
</div>
</div>
</div>
);
}
}```

ReactJS product id is not defined

I have the problem when I use the Reactjs, I'm really new to Reactjs, so maybe it's a easy problem:
class Product extends Component{
handleUpVote() {
this.props.onVote(this.props.id)
}
render(){
return(
<div className='item'>
<div className='middle aligned content'>
<div className='header'>
<a onClick={this.handleUpVote}>
<i className='large caret up icon'></i>
</a>
{this.props.votes}
</div>
</div>
</div>
)
}
}
class ProductList extends Component {
handleProductUpVote(prductId){
console.log(productId +' was upvoted')
}
render() {
const products1 = Data.sort((a,b) => (
b.votes-a.votes
));
const products=products1.map((product) =>{
return (
<div className='ui items'>
<Product
key={'product-'+product.id}
id={product.id}
onVote={this.handleProductUpVote}
/>
</div>
)})
return (
<div className='ui items'>
{products}
</div>
)
}}
export default ProductList;
At this line I am getting the error and i cant understand why:
this.props.onVote(this.props.id)
Forget binding this.
You need to pass the ID as a parameter to your click handler function.
Something like this:
class Product extends Component{
handleUpVote(id) {
this.props.onVote(id)
}
...
<Product
key={'product-'+product.id}
id={product.id}
onVote={() => this.handleProductUpVote(product.id)}
/>
}

Cannot print out object in ReactJS

I am a novice in ReactJS. I want to print out the image and text in the state object, but I do not know why it does not work when the system does not show any error. The following is my code
import React, { Component } from 'react';
class Asgn6 extends Component {
constructor(){
super();
this.state={
content:[
{srcImg:"../img/1.png", text:"Black"},
{srcImg:"../img/2.png", text:"Blue"},
{srcImg:"../img/3.png", text:"Green"}
]
}
}
add=() => {
}
render() {
return (
<div>
{this.state.content.map((obj, index)=> {
return (
<div key={index}>
<img src={require(obj.srcImg)} alt={obj.text}/>
<p>{obj.text}</p>
</div>
);
})}
);
<button onClick={this.add}>Add</button>
</div>
);
}
}
export default Asgn6;
The first rule you need to remember about automatic semicolon insertion is to keep whatever you return on the same line after return keyword. Otherwise this
return
<div>
<img src={require(obj.srcImg)} alt={obj.text}/>
<p key={index}>{obj.text}</p>
</div>
is equivalent to
return;
<div>
<img src={require(obj.srcImg)} alt={obj.text}/>
<p key={index}>{obj.text}</p>
</div>
Note, how semicolon is inserted after return.
Simple fix can be
return <div>
<img src={require(obj.srcImg)} alt={obj.text}/>
<p key={index}>{obj.text}</p>
</div>
or use parenthesis to group your returns:
return (
<div>
<img src={require(obj.srcImg)} alt={obj.text}/>
<p key={index}>{obj.text}</p>
</div>
)
<img src={obj.srcImg} alt={obj.text}/>
just do this.

Resources