Setting two state variable onClick in React

Asked
Active3 hr before
Viewed126 times

11 Answers

variableonclicksettingstatereact
90%

I am trying to set two state variables when a user clicks an image, my browser thinks that I am calling a second function, how do I assign both of these variables? I know I can't use && but I don't know how to do it properly, sorry if this is a silly question., That is because I am importing both of these setters from app.js and this is a component that I would like to dynamically update. I tried the suggestion below but now it throws "TypeError: setSelectedArtName is not a function" in the browser – TSav Jul 14 at 15:17 , What is the precise statement in Newtonian mechanics regarding the physical laws in all inertial frames?

I think you can do without &&:

<div className="img-wrap" key={doc.id}
                    onClick={() => {
                        setSelectedImg(doc.url);
          setSelectedArtName(doc.artName)}}
                >   
                    <img src={doc.url} alt={doc.artName} />
                    
                </div>

88%

Only react components have setState method. Working example:

import React from "react";
import ReactDOM from "react-dom";

export default class Nav extends React.Component {
constructor() {
  super();

  this.state = {
    navStatus: "navHide"
  };

  this.navClose = this.navClose.bind(this);
  this.navOpen = this.navOpen.bind(this);
}

navClose(e) {
  e.stopPropagation();
  this.setState({
    navStatus: "navHide"
  });
}

navOpen() {
  this.setState({
    navStatus: "navShow"
  });
}

render() {
  return(
    <nav onClick={this.navOpen}>
      <div id="myNav" className={this.state.navStatus}>
        <div className="navClose" onClick={this.navClose}>
          <object
            className="navCloseBtn"
            type="image/svg+xml"
            data="svg/close.svg"
          ></object>
        </div>                  
      </div>
    </nav>
  );
}
load more v
72%

You might have noticed the square brackets when we declare a state variable:,In a function, we already have setCount and count as variables so we don’t need this:,In a class, we need to call this.setState() to update the count state:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v
65%

With JSX you pass a function as the event handler, rather than a string.,For example, the HTML:,React events are named using camelCase, rather than lowercase.

<button onclick="activateLasers()">
   Activate Lasers
</button>
load more v
75%

We have to set initial state value inside constructor function and set click event handler of the element upon which click, results in changing state. Then pass the function to the click handler and change the state of the component inside the function using setState. The setState function used to change the state of the component directly or with the callback approach as mentioned below.,Example 1: This example illustrates how to change the state of the component on click.,How to change the state of react component on click?

Syntax:

this.setState({
   stateName: new - state - value
})
this.setState(st => {
   st.stateName = new - state - value
})
load more v
40%

State: While props allow you to pass data from a parent component to a child component, the state is used to change the component, well, state from within. Changes to the state also trigger a UI update.,Props: It allows you to pass data from a parent component to a child component.,Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop. For a better understanding look at this example.

22%

We also reviewed some common use cases of the onClick event handler in functional components, such as updating the state, calling multiple functions, and using synthetic events.,The onClick event handler also allows you to call multiple functions.,You can handle events in class components by binding them with the fat arrow function.

Take the following simple example written in HTML:

<button onclick="sayHello()">
   Say Hello
   <button>
load more v
60%

To render multiple elements we can do it as shown below:,But React hooks are now preferred for writing React components because they make the code shorter and easier to understand.,Instead of directly learning functional components with React hooks, you should first understand class-based components so it's easy to clear the basics.

How to Render Data in the UI in React

/n

To render anything on the screen, we use the ReactDOM.render method in React.

ReactDOM.render
load more v
48%

The onClick prop, in the example above, is being passed as an inline function that calls this.setState. The function is defined within the render method, often inline with JSX. In the context of React applications, this is a very popular and widely used pattern.,Let's understand this with a basic example of what an inline function might look like in a React application:,Simply put, an inline function is a function that is defined and passed down inside the render method of a React component.

 Pretag team - issue, fix, solve, resolve
23%

You can create a function that returns a function.,What you have to do is add a custom data-attribute to your HTML element.,Now Let’s see how to use this in the parent component.

You can create a function that returns a function.

class FooBar extends React.Component {
  handleClick = value => () => {
    console.log(value);
  };

  render() {
    return <button onClick={this.handleClick('Bar')}>Speak</button>;
  }
}
load more v
90%

The onClick attribute has special meaning here: it tells React to run a given function when the user clicks on the button. There are a couple of other things to note:,useState() creates a piece of state for a component, and its only parameter determines the initial value of that state. It returns two things: the state, and a function that can be used to update the state later.,In the above example, we're adding an onClick attribute to the <button> element. The value of that attribute is a function that triggers a simple alert.

const btn = document.querySelector('button');

btn.addEventListener('click', () => {
   alert("hi!");
});
load more v

Other "variable-onclick" queries related to "Setting two state variable onClick in React"