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 :
  • Why doesn't the .remove() method also affect the variable it's being set on?
  • React hooks error: Rendered more hooks than during the previous render
  • How to create a completely new Keyword in JavaScript?
  • When summing values from 2 arrays how can I cap the value in the new array?
  • A pop up window to login in
  • How to push spacebar action to array
  • How do i highlight a specific table row depending on the url
  • Truly Weak Reference Event Emitter / Dispatcher: is it possible?
  • Conditionally render a a background image based on current view using React Router
  • Can not retrieve component template while routing
  • How to keep the checkbox status after refreshing the page
  • Array of Object - divide information as per values in it
  • Calculating body style height (for horizontal scroll) in javascript not working
  • How to exclude certain values from randomly generated array
  • Change colour of selected <li>
  • Formatting date object in an Array with moment is giving an unexpected result
  • combineLatest operator alternative
  • 'object' is never reassigned. Use 'const' instead
  • What does the spread operator in ES6 convert to in older JavaScript? Is it costlier than array.concat?
  • Get duplicates in array of strings and count number of duplicates
  • How to fix React Redux and React Hook useEffect has a missing dependency: 'dispatch'
  • Call a ajax request only if there are ajax requests added to the list
  • Using the jQuery each function to count divs with the same class
  • FInding out the Harshad number
  • angular route is not working and not changing current view
  • Callback executed before function finishes execution
  • How to create subfolder and document on Firestore web?
  • Scroll algorithm -- improving fetch and display of data
  • New To Programming World
  • Using mongorestore to insert many documents into a temp collection
  • How to extend localStorage across devices (without DB)
  • How to do pre increment without using ++I?
  • Retrieve filterViewId from batchUpdate request addFilterView
  • What is the corresponding instanceof target for text nodes?
  • How to Test the API by Token on Postman?
  • How to set Bootstrap dropdown menu on hover?
  • In Slate.js editor.apply(operation) is not applying "split_node" operations correctly
  • No data in GET response
  • Javascript using if else to determine array value
  • Error when I run npm install Error: 404 Not Found: 7zip-bin@~4.1.0
  • I want to modified my JSON output using JS
  • Error in Entry module not found and in webpack
  • Submit button is not submitting the form after changing the button type
  • Why is the function created is not working.?
  • How can I do day timer with javascript?
  • Tap screen to trigger autofocus with getUserMedia
  • Unable to bind html table data to mvc controller Model
  • How can I simply work around a missing JS property in an object in an object?
  • How to add anything at a specific position in a string using vanilla javascript
  • using async methods inside of array.map() in javascript
  • Math.random() vs random() in Khan Academy Computer Programming
  • Call two functions with onPress in react native
  • Use a global variable inside promise javascript
  • Turn array of objects into array of properties
  • Would having a Pure Class concept make sense or not?
  • Why catch invoked with success promise?
  • Match whole word if it meets a condition
  • Inserting items into array with bracket syntax doesnt affect length?
  • adding value inside an input - React
  • How does setInterval() run independently of sequential execution?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org