logo
Tags down

shadow

Is there a different method to setState with e.target.value in functional component react using hooks?


By : Diahron Grismore
Date : July 31 2020, 12:00 PM
hope this fix your issue The big difference between the setter you get from useState and the class component setState method is that the setter from useState doesn't merge like setState does. So this:
code :
setNewNinja({
    [e.target.id]: e.target.value
});
setNewNinja({
    ...newNinjas, 
    [e.target.id]: e.target.value
});
setNewNinja(current => ({
    ...current, 
    [e.target.id]: e.target.value
}));
setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});


Share : facebook icon twitter icon

Do we still need functional setState way in react hooks?


By : user2616860
Date : March 29 2020, 07:55 AM
I wish this help you Yes, the behavior is similar.
React is batching the updates calls. When Writing:
code :
const handleClick = () => setCount(count + 1)
handleClick()
handleClick()
handleClick()
const handleClick = () =>
  setCount(prevCount => {
    return prevCount + 1;
});
handleClick()
handleClick()
handleClick()

react hooks setState does not properly re-render component


By : user2839514
Date : March 29 2020, 07:55 AM
should help you out I resolved the problem with a different approach. I set activeId state with initial value 'null' which updates with 'clicked button id' on button click. And load the child component only when 'button Id' matches 'activeId'.
And I also add this condition in child component.
code :
const isOpen = activeId === id;

  return (
    <Popper
      open={isOpen}
const ToggleMenuList = ({ navAdminList, navAdminItems, classes }) => {
  const [activeId, setActiveId] = useState(null);
  const anchorRef = useRef(null);
  const handleToggle = id => {
    setActiveId(id);
  };
  const handleClose = (event) => {
    if (anchorRef.current && anchorRef.current.include(event.target)) {
      return;
    }
    setActiveId(null);
  };

  return (
    <React.Fragment>
      <div className={`nav-menu ${classes.root}`}>
        {navAdminList.map(e => (
          <div key={e.id}>
            <Button
              ref={anchorRef}
              aria-owns={activeId === e.id ? 'menu-list-grow' : undefined}
              aria-haspopup="true"
              onClick={() => handleToggle(e.id)}
              className={e.className}
            >
              {e.name}
            </Button>
            {activeId === e.id && (
              <ToggleMenuItems
                id={e.id}
                activeId={activeId}
                handleClose={handleClose}
                anchorRef={anchorRef}
                items={navAdminItems[e.id]}
              />
            )}
          </div>
        ))}
      </div>
    </React.Fragment>
  );
};

const ToggleMenuItems = ({ id, activeId, handleClose, anchorRef, items }) => {
  const isOpen = activeId === id;

  return (
    <Popper
      open={isOpen}
      anchorEl={anchorRef.current}
      keepMounted
      transition
      disablePortal
    >
      {({ TransitionProps, placement }) => (
        <Grow
          {...TransitionProps}
          style={{
            transformOrigin:
              placement === 'bottom' ? 'center top' : 'center bottom',
          }}
        >
          <Paper id="menu-list-grow">
            <ClickAwayListener onClickAway={() => handleClose(id)}>
              <MenuList>
                {items.map(e => (
                  <MenuItem key={e.id} onClick={() => handleClose(id)}>
                    <Link to={e.to} className={e.className}>
                      {e.name}
                    </Link>
                  </MenuItem>
                ))}
              </MenuList>
            </ClickAwayListener>
          </Paper>
        </Grow>
      )}
    </Popper>
  );
};


React Class vs Functional Component: When using hooks and functional components one of my functions constantly re-render


By : user3236653
Date : March 29 2020, 07:55 AM
I wish this helpful for you So it turns out just wrapping things in useCallback doesn't work because I have other issues like button switching between disabled and active based on an answer being there.
I decided to re-write my component to have two states one that stores overall answers and the current answer in a separate state. This way I can wrap the save answer in a useCallback with only one dependency allowing for minmal re-renders but also my buttons become active/disabled.
code :
import React, { useState, useEffect, useCallback } from "react";
import PropTypes from "prop-types";
import { Row, Col } from "react-bootstrap";

// CC
import CCProgressBar from "../CCProgressBar";
import CCButton from "../CCButton";
import CCFlowAnswer from "../CCFlowAnswer/";

// Local Assets and CSS
import "./CCFlow.css";

const CCFlow = ({ questions, answers, wipeAnswers, handleSubmit, style }) => {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [usersAnswers, setUsersAnswers] = useState();
  const [currentAnswer, setCurrentAnswer] = useState(undefined);
  const [wipe, setWipe] = useState(false);

  useEffect(() => {
    setUsersAnswers(questions.map(() => undefined));
  }, [questions]);

  // Helpers
  function onLastQuestion() {
    return currentQuestion === questions.length - 1;
  }

  function progress() {
    const total = 100 / questions.length;
    return Math.round(total * (currentQuestion + 1));
  }

  function loadLastAnswer() {
    setCurrentAnswer(() => usersAnswers[currentQuestion - 1]);
    setCurrentQuestion(currentQuestion - 1);
  }

  function submitAnswers(answer, allAnswers, questionIndex) {
    const submittableAnswers = allAnswers;
    submittableAnswers[questionIndex] = answer;
    handleSubmit(submittableAnswers);
  }

  function cleanAnswers(allAnswers, wipeAnswers, wipe, questionIndex) {
    return wipe && wipeAnswers[questionIndex]
      ? allAnswers.map((answer, index) =>
          index > questionIndex ? undefined : answer
        )
      : allAnswers;
  }

  function loadNextAnswer(
    answer,
    allAnswers,
    wipeOptions,
    clear,
    questionIndex
  ) {
    const updatedUsersAnswers = cleanAnswers(
      allAnswers,
      wipeOptions,
      clear,
      questionIndex
    );
    updatedUsersAnswers[questionIndex] = answer;
    setWipe(false);
    setUsersAnswers(updatedUsersAnswers);
    setCurrentAnswer(
      updatedUsersAnswers[questionIndex + 1]
        ? updatedUsersAnswers[questionIndex + 1]
        : undefined
    );
    setCurrentQuestion(questionIndex + 1);
  }

  // Actions
  function moveForward(skip) {
    const ca = skip ? "None" : currentAnswer;
    currentQuestion === questions.length + 1
      ? submitAnswers(ca, usersAnswers, currentQuestion)
      : loadNextAnswer(ca, usersAnswers, wipeAnswers, wipe, currentQuestion);
  }

  function handleNextButtonClick() {
    moveForward();
  }

  function manualNextTrigger() {
    moveForward();
  }

  function handleSkip() {
    moveForward(true);
  }

  function handleBackButtonClick() {
    currentQuestion !== 0 ? loadLastAnswer() : window.history.back();
  }

  const saveAnswer = useCallback(answer => {
    setCurrentAnswer(answer);
    setWipe(() => true);
  }, []);

  return (
    <div className="ccQuestions" style={style ? style : {}}>
      <Row>
        <Col xs={3}>
          <h4 style={{ minHeight: "80px" }}>{questions[currentQuestion]} </h4>
          <div id="ccFlowRow">
            <CCProgressBar width="200px" now={progress()}></CCProgressBar>
            <span>{`${progress()}%`}</span>
          </div>
          <div id="ccFlowButtons">
            <CCButton variant="dark" onClick={handleBackButtonClick}>
              {currentQuestion === 0 ? "Exit" : "Back"}
            </CCButton>
            <CCButton
              style={{ marginLeft: "15px" }}
              variant={onLastQuestion() ? "primary" : "info"}
              onClick={handleNextButtonClick}
              disabled={currentAnswer ? false : true}
            >
              {onLastQuestion() ? "Create" : "Next"}
            </CCButton>
          </div>
        </Col>
        <Col xs={9}>
          <CCFlowAnswer
            FlowAnswer={answers[currentQuestion]}
            prevAnswer={
              currentQuestion !== 0 ? usersAnswers[currentQuestion - 1] : null
            }
            allAnswers={usersAnswers}
            handleAnswer={saveAnswer}
            answer={currentAnswer}
            handleSkip={handleSkip}
            next={manualNextTrigger}
          />
        </Col>
      </Row>
    </div>
  );
};

CCFlow.defaultProps = {
  questions: [],
  answers: [],
  wipeAnswers: []
};

CCFlow.propTypes = {
  style: PropTypes.object,
  questions: PropTypes.arrayOf(PropTypes.string),
  answers: PropTypes.arrayOf(PropTypes.elementType),
  handleSubmit: PropTypes.func,
  wipeAnswers: PropTypes.arrayOf(PropTypes.bool)
};

export default CCFlow;



React Hooks - refs for ScrollView in functional component with hooks?


By : user3414570
Date : March 29 2020, 07:55 AM
Any of those help Im converting a react native project from all class components to functional components with hooks. I have a messaging page with a ScrollView that auto scrolls to the bottom. How do i convert this to work in a functional component? Using ref and this.scrollView cause errors. , In the body of your component:
code :
function App(props) {    
   const scrollViewRef = useRef();
...
<ScrollView 
   ref={scrollViewRef}
   onContentSizeChange={(contentWidth, contentHeight)=> {scrollViewRef.current.scrollToEnd({animated: true})}}
>
{...content...}
</ScrollView>

Converting class based component to functional component using react hooks


By : MuslimZr
Date : March 29 2020, 07:55 AM
Hope this helps You have 2 options to achieve updating state values with hooks:
the first option would be to declare 2 state variables (or more, depending on the needs of the component)
code :
...
const [dragSource, setDragSource] = useState(...);
const [draggedItem, setDraggedItem] = useState(...);
...

const onDrag = (event, item, currentDropZoneId, currentDropZoneItems) => {
  event.preventDefault();
  console.log("source", currentDropZoneId);
  setDragSource(currentDropZoneId);
  setDraggedItem(item);
}

...

<Item
 draggable
 onDrag={event => onDrag(event, item, dropZone.id)}
 ey={item.id}
 />
...
const [state, setState] = useState({
  dragSource: ...,
  draggedItem: ...
});
...

const onDrag = (event, item, currentDropZoneId, currentDropZoneItems) => {
  event.preventDefault();
  console.log("source", currentDropZoneId);
  setState({
    dragSource: currentDropZoneId,
    draggedItem: item
  });
}

...

<Item
 draggable
 onDrag={event => onDrag(event, item, dropZone.id)}
 ey={item.id}
 />
Related Posts Related Posts :
  • How to decrypt the encrypted UID using firestore security rules?
  • javascript - if and or (||) statement
  • How to get overlay to position on an image?
  • cannot set checked of undefined (saving checkboxs w/ localStorage)
  • how can I send a data by ajax and the url has a variable value in the middle of the link
  • React Click Counter: Updating State of just one element
  • Having trouble with undefined output from this code below
  • Showing an image based on a number range in Javascript
  • Check which condition in IF statement is true
  • How do I reset the numbers after calculating the Total
  • Site loads slowly
  • How to insert href URL to Javascript var?
  • How can I use an array across multiple files?
  • Difference between $('.huyen') and $('.huyen')[0]
  • Using two array values in foreach loop
  • navigator.mediaDevices.enumerateDevices() returns empty labels
  • JavaScript positional property access in Objects
  • Is this possible to setInterval with custom ID so I can clear it later on from another services?
  • How to focus bootstrap select picker
  • Calling firebase functions returns null
  • Set a variable equal to null if it is not included in an array?
  • Remove Duplicate object from Array Deep Check
  • Check if array of objects key is empty and splice it
  • How to find next birthday date from list of date from date now?
  • Reorder array of objects based on array of strings?
  • Replace ISO-Date with normal Date in HTML Document via Widget
  • React setState not changing the state
  • Bitwise operations in JavaScript
  • react slide out menu state = not setting state?
  • .map() function and deleting a row from a table with ReactJS
  • Vanilla JavaScript in Svelte
  • Filter My Array / JSON Data (including multi values) Based on Multiple Criteria in JavaScript?
  • Unnecessary rerenders with useContext
  • Implement HTML input phone mask XXX-XXX-XXXX
  • create variable by matching variable value to object value?
  • Parsing Data in Google Sheets From an Object
  • How to obtain a user input value from an image input in Javascript?
  • Is it posible to implement functions that use non blocking setTimeout synchronically?
  • What would be consider as my local scope in this function?
  • regex expression for string.split() that splits a string on urls
  • Vue props become null on $router.go(-1)
  • How can I set my local date in javaScript
  • Why my state does not change on click event with setState
  • How to fetch data from API using id in reactJS?
  • What is the problem in this recursive javascript function? [JS]
  • How to store & retrieve an object as a value in option of select element?
  • Select Text in DIV with specific range using JavaScript
  • JavaScript error executing a function: 2 arguments required but only 1 present
  • How to remove a specific character from array in JS?
  • Get Text content of 3rd <p> element inside <div> element
  • HTML li element will not except
  • How can I render nested objects and arrays in JSX?
  • using .find or .index of inside .find
  • Unable to add to an array of objects copied from state
  • Find an object properties by searching for keys by a string, and if one is true, return as true
  • Why does awaiting a setInterval promise inside of a while loop cause the amount of calls to stack up?
  • How to send data attribute to php variable using jquery?
  • In Javascript or jQuery how to scroll so that an element inside another div is centered vertically and horizontally
  • How to create an animated stackoverflow icon
  • Why is my javascript function being printed as undefined?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org