logo
down
shadow

Having trouble with multiple active states in ReactJS


Having trouble with multiple active states in ReactJS

By : Elvis07
Date : October 22 2020, 08:10 PM
wish helps you The problem is this active={this.state.active} You manage all the button with only one state.active. U need to make one state per button. Here and example
code :
        state {
            btnA:false,
            btnB:false,
            btnC:false
        }

        changeState = (btn) => {
            if(btn === 'a'){
                this.setState( prevState => {
                    return {
                        btnA:  !prevState.btnA
                    }
                })
            }
            .... same for btnB and btn C
        }
        ...

        return (
            <div>
                <button onClick={this.state.changeState('a')} >{this.state.btnA?'Btn A is active':'Btn A is not active'}<button>
                <button onClick={this.state.changeState('b')} >{this.state.btnB?'Btn B is active':'Btn B is not active'}<button>
                <button onClick={this.state.changeState('c')} >{this.state.btnB?'Btn C is active':'Btn C is not active'}<button>
            </div>
        )


Share : facebook icon twitter icon
States in ReactJs using ES6 and ES7

States in ReactJs using ES6 and ES7


By : Precious Xyza
Date : March 29 2020, 07:55 AM
I wish this help you in ES6, The React team decided a more idiomatic way of initializing state was simply to store it in an instance variable setup in the constructor. This means you can refactor away your getInitialState method by moving its return value to be assigned to the this.state instance variable in your class' constructor.
code :
import React, { Component } from 'react';

class LikeButton extends Component {
  constructor() {
    super();
    this.state = { liked : false };
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState({
        liked : !this.state.liked
    });
  }

  render() {
    const text = this.state.liked ? 'like' : 'haven\'t liked';

    return (
        <p onClick={this.handleClick}>{`You ${text} this. Click to toggle.`}</p>
    );
  }
}
import React, { Component } from 'react';

class LikeButton extends Component {
  state = {
    liked : false
  }

  render() {
    const text = this.state.liked ? 'like' : 'haven\'t liked';
    const handleClick = ()=>{
      this.setState({
        liked : !this.state.liked
      });
    }

    return (
        <p onClick={this.handleClick}>{`You ${text} this. Click to toggle.`}</p>
    );
  }
}
reactjs : ShouldComponentUpdate for states

reactjs : ShouldComponentUpdate for states


By : Romina
Date : March 29 2020, 07:55 AM
I hope this helps you . The shouldComponentUpdate(nextProps, nextState) method works for both props and state. In your example, after the onClick event the following method is fired by React.
code :
shouldComponentUpdate(nextProps, nextState) {
  return this.state.value != nextState.value;
}
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      value: true,
      countOfClicks: 0
    };
    this.pickRandom = this.pickRandom.bind(this);
  }

  pickRandom() {
    this.setState({
      value: Math.random() > 0.5, // randomly picks true or false
      countOfClicks: this.state.countOfClicks + 1
    });
  }

  // comment out the below to re-render on every click
  shouldComponentUpdate(nextProps, nextState) {
    return this.state.value != nextState.value;
  }

  render() {
    return (
      <div>
        shouldComponentUpdate demo 
        <p><b>{this.state.value.toString()}</b></p>
        <p>Count of clicks: <b>{this.state.countOfClicks}</b></p>
        <button onClick={this.pickRandom}>
          Click to randomly select: true or false
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
Having trouble managing states in Reactjs

Having trouble managing states in Reactjs


By : Darren Bowen
Date : March 29 2020, 07:55 AM
seems to work fine Here is one possible answer if I understood you right. I'm totally mimicking the situation so this is not a complete solution for you.
code :
class App extends React.Component {
  state = {
    answers: [ "1", "19", "21", "90", "-1" ],
    selected: {},
  }

  handleClick = e => {
    const {answer} = e.target.dataset;
    this.setState({selected:{
      [answer]: !!answer,
    }})
  };


  render() {
    const {answers} = this.state;
    console.log(this.state.selected);
    return (
      <div>
      <ul>
        {
          answers.map( answer => 
            <li
            data-answer={answer}
            className={
                  this.state.selected[answer] ? 'colored' : ''
            }
            onClick={this.handleClick}
            >{answer}
            </li>
          )
        }
      </ul>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
.colored {
  color: red;
}
<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>
handleClick2 = answer =>
   this.setState({
     selected: {
       [answer]: !!answer,
     }
})
onClick={this.handleClick2.bind(this, answer)}
class App extends React.Component {
  state = {
    answers: [ "1", "19", "21", "90", "-1" ],
    selected: {},
  }

  handleClick = e => {
    const {index} = e.target.dataset;
    this.setState({selected:{
      [index]: !!index,
    }})
  };


  render() {
    const {answers} = this.state;
    console.log(this.state.selected);
    return (
      <div>
      <ul>
        {
          answers.map( (answer, index) => 
            <li
            data-index={index}
            className={
                  this.state.selected[index] ? 'colored' : ''
            }
            onClick={this.handleClick}
            >{answer}
            </li>
          )
        }
      </ul>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
.colored {
  color: red;
 }
<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>
const {answers} = this.state
const answers = this.state.answers;
const { one, two, three } = object;
const one = object.one;
const two = object.two;
const three = object.three;
this.setState({selected:{ [answer]: !!answer }})
selected: {
    "19": !!"19"
}
  handleClick = answer => {
    this.setState(prevState =>
      ({
        selected: {
          [answer]: !prevState.selected.answer,
        }
      })
    )
  };
const answers = ["1", "19", "21", "90", "-1"]
const AnswerChoices = () => (
  <SpecificAnswerChoice answers={answers} />
)

class SpecificAnswerChoice extends React.Component {
  state = {
    selected: {},
  }

  handleClick = answer =>
    this.setState(prevState =>
      ({
        selected: {
          [answer]: !prevState.selected.answer,
        }
      })
    );

  
  render() {
    const { answers } = this.props;
    return (
      <div>
        {
          answers.map( individualAnswer => (
            <EachIndividualAnswer
            individualAnswer={individualAnswer}
            onClick={this.handleClick}
            selected={this.state.selected}
            key={individualAnswer}
          />
          ) )
        }
      </div>
    )
  }
}

// Again, destructring. Instead of (props) we use ({....})
// and pick our individual props here.
const EachIndividualAnswer = ({selected,individualAnswer, onClick}) => {
  const handleClick = () => onClick(individualAnswer)
  return (
    <div>
    <ul>
        {
          <li
            onClick={handleClick}
            className={
              selected[individualAnswer] ? 'colored' : ''
            }
          >{individualAnswer}
          </li>
        }
      </ul>
    </div>
  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<AnswerChoices />, rootElement);
.colored {
  color: red;
}
<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>
Updating nested states in reactjs

Updating nested states in reactjs


By : Michiel de Rond
Date : March 29 2020, 07:55 AM
around this issue You are setting the entire state in newForm. Just limit it to the form object:
code :
let newForm = {
  ...this.state.form,
  pages: [
    ...this.state.form.pages,
    pageData
  ]
};

console.log('newForm', newForm);

this.setState({
  form: newForm
});
ui-sref-active on multiple states

ui-sref-active on multiple states


By : Jennifer Bledsoe
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I want the ui-sref-active to be active on on multiple states. This is what I have , I would recomment to use the includedByState filter.
Related Posts Related Posts :
  • Broken "if" statement in JavaScript code…
  • Trying to create a display/hide toggle content using jQuery?
  • How to transition perspective-origin specifically?
  • Why does my nested for loop for creatDocumentFragment run the outside for loop only once?
  • How to prevent our URL from Cross-site scripting (XSS)?
  • Add change text on click with existing onclick button in jquery
  • How do I replace a <li> element in HTML with something different using jQuery?
  • How does Facebook update likes withot refresh?
  • Do mobile browsers support 4k video using HTML5 video tag?
  • Node.js pass variable/object from one module and return it
  • How do I access arrays on the asm.js heap from Javascript code, when the array's type is not Uint8?
  • How to modify fullcalendar columnFormat with bracket?
  • Nodejs How To Iterate With a Promise
  • React: setState is not defined, I already tried binding this
  • How to get text of form child when an input element is clicked on
  • How to avoid using setTimeout to wait for Promises to resolve?
  • jQuery - Check checkbox and disable other if has different value
  • Can't use fnReloadAjax datatable
  • Unfamiliar use of square brackets during multiple variable declaration in Javascript
  • How do I assign my .reduce function output to a variable?
  • Populate items from an array into different options tag
  • Javascript Regular Expressions Email Address
  • How to have multiple Flatlists with filtered data in React Native
  • Scroll to Top of Document After Param Change in Angular 4?
  • Sweetalert2 Ajax - post input data
  • Can I build a split slider using slick?
  • How can I customize a permission request popup for push notifications in a browser?
  • Find array in another array and get index of result
  • Service worker promise.then is not defined
  • how to keep validation off if some section of forms not showing during form-filling in jquery
  • Store string values to array inside a loop
  • How can I search through this JS object?
  • Accordion close animation not working. It opens (with animation) and closes (with no animation)
  • Mocha, nodejs promise test can't finish because lack of done
  • No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefor
  • delete certain parts of a text text in javascript
  • Angular 2 D3 tree is not rendering correctly
  • Update selected item from Flatlist in Firebase using React Native
  • Trouble understanding Javascript closure example
  • edit canvas pixel coordinates
  • Insert script into a script
  • Axios is returning a string called "Array" instead of an object
  • How to submit forms with QuillJs and body-parser?
  • Design pattern for sitewide configuration in Angular JS
  • firestore orderby on subproperty (subcollection)
  • How does angular method decorator work?
  • function not returning JSON property value - node.js
  • How do I pull from Google Analytics and create a trending threads section based on most popular content
  • Rails 5: JavaScript runs but doesn't appear in browser
  • Insert PHP functions into Javascript
  • want to make the revolution slider's height dynamic based on jQuery(window).height()
  • how can convert a base64 svg image to base64 image png
  • new table row is added under the first cell in the header
  • Why is AWS SQS so slow?
  • how to read a json config file and setting that parameter to ajax
  • object literal. Inexact type is incompatible with exact type (no object spread)
  • Define globals when bundling to umd or commonjs
  • How do I store functions with their parameters in an array and execute them sequentially?
  • Overcoming antialiasing on canvas lines for mouse event
  • Scrapy splash not returning results
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org