Reactjs : Update value of a component on click - javascript

I have built a minimal ReactJS component to update the number of likes. All works well but the count does not update when clicked. I tried following several answers but cannot figure out why.
See the code:
import React, {useState} from 'react';
class GiveLikes extends React.Component {
// set the initial value of the likes
state = {likes:0};
// Function is called every time "likes" is clicked
likes_count = (likes) =>{
// Counter state is incremented
this.state({likes: likes+1});
}
render() {
return (
<>
<h2> {this.state.likes} </h2>
<div className="buttons">
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginRight: '5px',
backgroundColor: 'green',
borderRadius: '8%',
color: 'white',
}}
onClick={() => this.likes_count}>Likes
</button>
</div>
</>
)
}
}
export default GiveLikes;
The above code will render the following on the web browser. Clicking the "Likes" should update the value of the count, but unfortunately it does not.

Declare a constructor and initialize your state,
Use an arrow function on your likes_count() method
Use this.setState({likes: this.state.likes +1}); instead of this.state({likes: this.state.likes +1});
import React, {useState} from 'react';
class GiveLikes extends React.Component {
constructor(props) {
super(props);
this.state = {likes: 0};
}
likes_count = () => {
this.setState({likes: this.state.likes +1});
}
render() {
return (
<>
<h2> {this.state.likes} </h2>
<div className="buttons">
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginRight: '5px',
backgroundColor: 'green',
borderRadius: '8%',
color: 'white',
}}
onClick={this.likes_count}>Likes
</button>
</div>
</>
)
}
}
export default GiveLikes;

Edit:
The summary of this answer is that the state does not exist because there is no constructor for this.state
I believe the answer to be is Props are never to be updated. We are to use them as is. Sounds rigid right? But React has its reasons behind this rule and I’m pretty convinced by their reasoning. The only caveat is, though, that there are situations where we might need to initiate the update of a prop. And we will soon know how.
Consider the following line of code from a parent component:
<MyChild childName={this.state.parentName} />
Now if there is any change of name required, parentName will be changed in the parent and that change will automatically be communicated to the child as is the case with the React mechanism. This setup works in most of the scenarios.
But what if you need to update the prop of the child component, and the knowledge of the change required and the trigger to change it is only known to the child? Considering the ways of React, data can only flow from top-to-bottom i.e., from parent-to-child. So then how are we to communicate to the parent that a change to prop is required?
Answer from the following source: https://www.freecodecamp.org/news/how-to-update-a-components-prop-in-react-js-oh-yes-it-s-possible-f9d26f1c4c6d/
I've only shown the parts you need to read nothing else. Please analyse your code properly next time, this isn't a hard thing to do .

You forgot to call the function -
onClick={() => this.likes_count()}
Also, Instead of passing likes you need to use the data from state and then update it like -
likes_count = () => {
let likes = this.state.likes;
this.setState({ likes: likes + 1 });
};

Add a constructor and initialize this.state otherwise it won't be exists.
What happens is every time you re-render your component (by state or props change) you will re-create the your state again and again with {likes: 0} and it will not work.
Also, you are mixing class component and functional component syntax style, which will lead to more bugs and issues with react and your code.
Moreover, you need to put a function that will be called in onClick but you created a function that returns a function, and it is wrong in your case.
Another issue is to set your likes state using this.setState and not just calling state as a function.
import React from 'react';
class GiveLikes extends React.Component {
constructor(props) {
super(props);
this.state = {likes: 0};
}
likes_count = () => {
this.setState ({likes: this.state.likes +1});
}
render() {
return (
<>
<h2> {this.state.likes} </h2>
<div className="buttons">
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginRight: '5px',
backgroundColor: 'green',
borderRadius: '8%',
color: 'white',
}}
onClick={this.likes_count}>Likes
</button>
</div>
</>
)
}
}
export default GiveLikes;
Read about react.
Focus on your first component (look for examples with counters components online).
Don't rush into things without fully understand. React is fun.

Related

How to get value from element in react js?

This is my very first app in React. I have created the component and when a user adds text to textArea and clicks on the button, "Download Pdf", I want to pass defaultValue to convertToPdf function.
How do i do that? Basically, I am trying to create a PDF downloader. Any help will be appreciated.
pdfComponent.js
import React, { Component } from "react";
import autosize from "autosize";
import Button from '#material-ui/core/Button';
export class PDFEditorComponent extends Component {
componentDidMount() {
this.textarea.focus();
autosize(this.textarea);
}
convertToPdf() {
this.setState(this.textarea);
console.log("TEXT", this.textarea);
}
render() {
const style = {
maxHeight: "175px",
minHeight: "450px",
minWidth: "800px",
resize: "none",
padding: "9px",
boxSizing: "border-box",
fontSize: "15px"
};
return (
<div>
PDF Downloader
<br />
<br />
<textarea
style={style}
ref={c => (this.textarea = c)}
placeholder="Paste pdf data"
rows={1}
defaultValue=""
/>
<br />
<Button
variant="contained"
color="primary"
onClick={() => this.convertToPdf(this.textarea)}
>
Download Pdf
</Button>
</div>
);
}
}
Bulletpoints:
Actually create a ref for your textarea (in constructor)
constructor(props) {
super(props);
this.textareaRef = React.createRef();
}
then pass it to your textarea element like this
ref={this.textareaRef}
In your convertToPdf() use it like so
this.setState({value: this.textareaRef.current.value})
React state consists of key-value pairs, so you should initialize it in constructor like so
this.state = {
value: null;
}
and then whenever you want to change it (only from within this component), you call setState(), like I did in p. 2
You are mixing html elements with JS variables: you can't call this.textarea, because it's not a variable (nor constant), so remove all such references to it. In React the only way to access DOM elements is by refs (which you already kind of tried, I corrected you in p. 1).
Enjoy React, it's great :)

How to pass function and data from component class to stateless class in React Native?

I am working with react native and I want to pass function and some data from Component class to another Stateless class, but I could not make to passing function and data part.
Here you can see my Component class:
class Classroom extends Component {
constructor(props, context) {
super(props, context);
};
state = {
isLightOn: false,
title : "Turn light on "
}
onPress() {
this.setState({isLightOn: !this.state.isLightOn})
console.log(this.state.isLightOn)
this.setState({title:this.state.isLightOn===false ?"Turn light off":"Turn light on"})
}
render() {
return (
<View style={styles.blue}>
<LightBulb isLightOn={this.state.isLightOn}> </LightBulb>
<LightButton onPress={this.onPress} isLightOn={this.state.isLightOn} title={this.state.title} > </LightButton>
</View>
);
}
}
Firstly, I want to pass isLightOn and title datas to my LightButton class (which mean to my stateless class). After that, I want to use onPress function inside of my Stateless class, but I cannot use. I am taking that error:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I also LightButton onPress={this.onPress} remove parenthesis, but still taking error.
Here is my my Stateless class
const LightButton = ({onPress,isLightOn,title}) => (
<View style={styles.red}>
<Button
title= {title}
onPress={() => {}
}
/>
</View>
)
I want to use onPress function and datas inside of the this class.
As a result, How can I pass function and data to that class?
The main issue here is that you need to declare onPress using an arrow function or bind it to the component's this value within the constructor. Otherwise it wouldn't have access to the correct this value. Other than that, the way you were passing props into components is perfectly fine.
I also merged your two set state calls in onPress to one as it's easier.
In LightButton, I set it up like this to pass the onPress function down to the button:
const LightButton = ({ onPress, isLightOn, title }) => (
<div style={{backgroundColor:'red'}}>
<Button title={title} onPress={onPress} />
</div>
);
(I set it up using react, but the issues at hand are more of a JS issue than a React/ReactNative one, so the advice should still be valid :) )
const { Component } = React;
const View = 'div';
const Button = (({title,onPress})=><button onClick={onPress}>{title}</button>);
const LightBulb = ({ isLightOn }) => {
return <div className={'LightBulb' + (isLightOn ? ' on' : '')} />;
};
const LightButton = ({ onPress, isLightOn, title }) => (
<div style={{backgroundColor:'red'}}>
<Button title={title} onPress={onPress} />
</div>
);
class Classroom extends Component {
state = {
isLightOn: false,
title: 'Turn light on ',
};
onPress=()=> {
console.log(this.state.isLightOn);
this.setState({
title:
this.state.isLightOn === false ? 'Turn light off' : 'Turn light on',
isLightOn: !this.state.isLightOn
});
}
render() {
return (
<div style={{backgroundColor:'blue'}}>
<LightBulb isLightOn={this.state.isLightOn}> </LightBulb>
<LightButton
onPress={this.onPress}
isLightOn={this.state.isLightOn}
title={this.state.title}
>Button</LightButton>
</div>
);
}
}
ReactDOM.render(<Classroom />, document.querySelector('#root'));
.LightBulb {
height: 50px;
width: 50px;
border-radius: 50px;
background-color: black;
}
.LightBulb.on {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
You can assign it like
const LightButton = ({onPress,isLightOn,title}) => (
...
onPress={onPress}
...
or with an arrow function if you need to pass arg inside
onPress={()=>onPress(someArg)}
do notice that you either don't put () at all, or twice () => func() for not run the function while it is just loads and not clicked.
unrelated directly to your issue but something that you encounter is inside onPress by doing like so
this.setState({isLightOn: !this.state.isLightOn})
console.log(this.state.isLightOn)
this.setState({title:this.state.isLightOn===false ?"Turn light off":"Turn light on"})
setState it is an async call, and therefore second setState usage not guaranteed to refer the state as you expect, use setState({ ... }, () => callback()) or all at one line and accords to prev state
this.setState({isLightOn: !this.state.isLightOn, title: !this.state.isLightOn===false ?"Turn light off":"Turn light on"})
First thing you did wrong is your state instantiating !
you need to instantiate your state in the constructor block like:
constructor(props, context) {
super(props, context);
this.state = { counter: 0 };
}
onPress() you use this for your function which is not recommended in react native or any other language , those are dedicated functions and methods of React Native
For passing a parameter or calling a function it is better to use these patterns ====>
onPress={() => urFunction()} with parenthesis or
onPress={urFunction} without parenthesis
Do the modifications I hope it helps <3

react-native : Can I use props in a method?

I have my class and I have a method and I am wondering if I could use props inside a mehtod.
Notice I try to use props in methodTwo. Is this possible? If not, is there a way I could use props in method?
import React from 'react';
import { Image, Text, View } from 'react-native';
export default class Test extends React.PureComponent {
methodOne = () => {
this.setState({
one:false,
two:false,
three:false
})
}
methodTwo = () => {
this.setState({
one:false,
two:false,
//I want to use props
three:this.props.three
})
}
render() {
return (
<View style={{ backgroundColor: 'transparent', alignItems: 'center' }}>
<Button title='one' onPress={()=>this.methodOne()}/>
// I could call i like this?
<Test three='newState'/>
</View>
);
}
}
methodTwo = () => {
this.setState({
one:false,
two:false,
three:this.props.three
})
}
props-> is the value that is been transferred from parent component to child component.
In class based component you fetch the value by using this.props.Attribute_name and in functional based component you can fetch the value using props.Attribute_name (mind functional based component dont have any concept of this)
if you want to use this.props.three ,then in parent component call (the component calling this particular component) <Test three="anyValue" /> then you can easily get this value in child component.
class Cat extends React.Component {
render() {
const mouse = this.props.mouse;
return (
<img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
);
}
}
class MouseWithCat extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}
handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
{/*
We could just swap out the <p> for a <Cat> here ... but then
we would need to create a separate <MouseWithSomethingElse>
component every time we need to use it, so <MouseWithCat>
isn't really reusable yet.
*/}
<Cat mouse={this.state} />
</div>
);
}
}
class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<MouseWithCat />
</div>
);
}
}
The props are accessible to whole of the class scope with the syntax this.props.xxxx if you have passed it from its parent component. SO you can use in methodOne too.
You can use props inside a method. Any specific error you are facing ?.

React Native - change component style by key

I know that in html and javascript are able to change it own css style by id and class , in react native, how to set / change the component style. I have map a list of component, and each of them have set a key value. When I call a function, I would like to change one of the component style.
eg: change the key is 2 component style
_RenderSpecialItem(){
return this.state.speciallist.map((item, i)=>{
return(
<SpecialItem
key={i}
/>
);
});
}
_ChangeStyle(){
//do something
}
You can use Direct Manipulation but it's not a good practice, for more please read
Direct manipulation will not be a tool that you reach for frequently; you will typically only be using it for creating continuous animations to avoid the overhead of rendering the component ...
in the link. Otherwise, you should you set state in component and change state to update the style
e.g.
first set ref to the component :
<SpecialItem
key={i}
ref={(thisItem) => this[`item-${i}`] = thisItem}
/>
then setNativeProps :
_ChangeStyle() {
this['item-2'].setNativeProps({style: {/* your style here */}});
}
full example
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
speciallist: ['aaa', 'bbb', 'ccc']
}
}
componentDidMount() {
this['text-0'].setNativeProps({style: {fontSize: "10"}});
this['text-1'].setNativeProps({style: {fontSize: "20"}});
this['text-2'].setNativeProps({style: {fontSize: "30"}});
}
render() {
return (
<View style={styles.container}>
{
this.state.speciallist.map((item, i)=>(
<Text
key={`text-${i}`}
ref={(thisItem) => this[`text-${i}`] = thisItem}
>
{item}
</Text>
))
}
</View>
);
}
}

React removing an element when onClick

I am trying to remove a div when onClick is pressed. The div exists on my parent component where I have
render() {
const listPlayers = players.map(player => (
<Counter
key={player.id}
player={player}
name={player.name}
sortableGroupDecorator={this.sortableGroupDecorator}
decrementCountTotal={this.decrementCountTotal}
incrementCountTotal={this.incrementCountTotal}
removePlayer={this.removePlayer}
handleClick={player}
/>
));
return (
<ContainLeft style={{ alignItems: 'center' }}>
<ProjectTitle>Score Keeper</ProjectTitle>
<Copy>
A sortable list of players that with adjustable scores. Warning, don't go negative!
</Copy>
<div>
<Stats totalScore={this.state.totalScore} players={players} />
{listPlayers}
</div>
</ContainLeft>
);
}
It passes props to the child component where the button to delete the div, here
return (
<div
style={{ display: this.state.displayInfo }}
className="group-list"
ref={sortableGroupDecorator}
id="cell"
>
<CountCell style={{ background: this.state.color }}>
<Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
<Col>
<DeleteButton onClick={removePlayer}>
<Icon name="delete" className="delete-adjust fa-minus-circle" />
</DeleteButton>
</Col>
(I snipped the rest of the code because it was long and not useful here)
The array (a separate file) is imported into the Parent component and it reads like this
const players = [
{
name: 'Jabba',
score: 10,
id: 11
},
{
name: 'Han',
score: 10,
id: 1
},
{
name: 'Rey',
score: 30,
id: 10
}
];
export default players;
So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"
On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.
The function I'm building (in progress, I'm still a little lost here) is:
removePlayer() {
console.log('this was removed');
players.splice(2, 0, 'Luke', 'Vader');
}
which is mapped over here as a prop
const listPlayers = players.map(player => (
<Counter
key={player.id}
player={player}
name={player.name}
sortableGroupDecorator={this.sortableGroupDecorator}
decrementCountTotal={this.decrementCountTotal}
incrementCountTotal={this.incrementCountTotal}
removePlayer={this.removePlayer}
handleClick={player}
/>
));
And passed into the child here:
render() {
const {
name,
sortableGroupDecorator,
decrementCountTotal,
incrementCountTotal,
removePlayer
} = this.props;
return (
<div
style={{ display: this.state.displayInfo }}
className="group-list"
ref={sortableGroupDecorator}
id="cell"
>
<CountCell style={{ background: this.state.color }}>
<Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
<Col>
<DeleteButton onClick={removePlayer}>
<Icon name="delete" className="delete-adjust fa-minus-circle" />
</DeleteButton>
I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages. Thanks for helping out in advance
We sorted it out in chat. Like expected, it was a problem with the state.
I made a small semi-pseudo snippet with comments as explanation:
import React, { Component } from 'react';
// Your player constant, outside the scope of any React component
// This pretty much just lives in your browser as a plain object.
const players = [
{
name: 'Jabba',
score: 10,
id: 11
},
{
name: 'Han',
score: 10,
id: 1
},
{
name: 'Rey',
score: 30,
id: 10
}
];
class App extends Component {
constructor() {
super();
this.state = {
players, // ES6 Syntax, same as players: players
// Add all your other stuff here
};
}
removePlayer(id) {
const newState = this.state;
const index = newState.players.findIndex(a => a.id === id);
if (index === -1) return;
newState.players.splice(index, 1);
this.setState(newState); // This will update the state and trigger a rerender of the components
}
render() {
const listPlayers = this.state.players.map(player => { // Note the this.state, this is important for React to see changes in the data and thus rerender the Component
<Counter
..
removePlayer={this.removePlayer.bind(this)} //bind this to stay in the context of the parent component
/>
});
return (
<div>
{listPlayers}
</div>
);
}
}
//////////////////////////////////////// Child component
....
<DeleteButton onClick={() => this.props.removePlayer(this.props.player.id)}>
....
Here is how i solved this
i've added an id to the element
and then with function remove i detroyed it
const closenotif = () => document.getElementById("notif").remove()
<div id="notif">
<button onClick={destroy}> close </button>
</div>
NB : the element is destroyed in the current document
so in the current render
on Next JS this works perfectly
if you are using a live rendering with react this probably won't work
i'll suggest you to work with states in that case
Little confused about how the whole app works, but I will try to help you.
To make react changes to the dom, you have to put players in the state. So, in the removePlayer you make a copy of this.state.players in a local variable (just to not change the array directly in state, it's a good practice), then you make the split in this local variable and finally you setState({ players: localPlayers}).
This way the "div" will be removed.

Categories

Resources