React: cant get output inside a functional component

Asked
Active3 hr before
Viewed126 times

9 Answers

componentreact
90%

Thanks for contributing an answer to Stack Overflow!, Stack Overflow Public questions & answers , Don't be that account: buying and selling reputation and bounties

A way to fix that:

{exercices_.map(([category, array]) => {
          return <Typography>{category}</Typography>;
})}
load more v
88%

Do something when the component renders,In both cases, the components simply output a paragraph element with content. Notice that the functional version, besides the same call to ReactDOM.render() has no interaction with any APIs. It is just a normal JavaScript function.,Do something when the component unmounts, i.e., clean up

class QuipComponent extends React.Component {  render() {    return <p>What gets us into trouble is not what we don't know. It's what we know for sure that just ain't so.</p>;  }}<div id="app"></div>ReactDOM.render(<QuipComponent />, document.querySelector("#app"));
load more v
72%

This way, React will just compare the output of the function, but not the function itself (as it would, in the case if we use it as a component). Since CounterWithWeekday's output is ok nothing gets re-mounted.,However, if functional components are just functions, why wouldn't we call them directly? Why do we use <Component /> syntax instead?,A function that could be used as a component is not necessarily will be used as a component. So, to be a component, it needs to be used as <Text /> instead.

const App = () => {
  const [total, setTotal] = useState(0);
  const incrementTotal = () => setTotal(currentTotal => currentTotal + 1);

  return (
    <div className="App">
      <div>
        <h4>Total Clicks: {total}</h4>
      </div>
      <div className="CountersContainer">
        <Counter onClick={incrementTotal} />
        <Counter onClick={incrementTotal} />
        <Counter onClick={incrementTotal} />
      </div>
    </div>
  );
};
load more v
65%

The simplest way to define a component is to write a JavaScript function:,Don’t be afraid to split components into smaller components.,For example, consider this Comment component:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
load more v
75%

I will start by declaring the variable inside the functional component.,React Hooks enables us to define state into such functional components.,Passing an update function allows you to access the current state value inside the updater.

To answer, it is as simple as creating a function returning an HTML-like syntax.

import React from 'react';

function Counter({n}) {
  return (
    <div>{n}</div>
  );
}

export default Counter;
load more v
40%

There’s one aspect of JavaScript that always has me pulling my hair: closures. I work with React a lot, and the overlap there is that they can sometimes be the cause of stale props and state. We’ll get into exactly what that means, but the trouble is that the data we use to build our UI can be totally wrong in unexpected ways, which is, you know, bad.,Give it another try. Now it works perfectly whether you use states or props.,My take is to abstract away the handleAlertClick since it does not depend on our UI logic, and then expose access to the state through a getter, rather than the resolved value.

e.g.

const [count, setCount] = useState(0);
const ref = useRef(count);

useEffect(() => {
   ref.current = count
}, [count])
load more v
22%

React functional components are plain JavaScript functions. It is not possible to persist state in local variables as these are initialized every time the function is evaluated. Thus to maintain state inside the function, React provides several hooks:,For functional components:,Function internal variables will get initialized during each execution. Thus it is important to keep them optimized. Costly computations should be cached. memoization is a recommended pattern.

const [isAuthenticated, setIsAuthenticated] = useState(false)
const initialState = { count: 0 };const reducer = (state, action) => {  switch (action.type) {    case "increment":      return { count: state.count + 1 };    case "decrement":      return { count: state.count - 1 };    default:      throw new Error();  }};const increment = () => ({ type: "increment" });const decrement = () => ({ type: "decrement" });function Counter() {  const [state, dispatch] = useReducer(reducer, initialState);  return (    <>      Count: {state.count}      <button onClick={() => dispatch(increment())}>+</button>      <button onClick={() => dispatch(decrement())}>-</button>    </>  );}
const myPromise = useRef();
const onClick = () => {
   myPromise.current = fetch('/myapi');
}
load more v
60%

This is shorter and more readable than the class-based original. Unlike the class component, you can’t access a state instance property or setState() method. Instead, useState() is called to setup the state and obtain an updater function.,If you pass a function to useState(), React will call it and use its return value as the initial state value.,The stateful properties now have their own state variables and update functions.

class MyComponent extends React.Component {
 
    state = {value: 1};
 
    this.updateState = () => this.setState({value: (this.state.value + 1)});
 
    render() {
        return (
            <div>
                <p>{this.state.value}</p>
                <button onClick={this.updateState}Increment Value</button>
            </div>
        );
    }
 
}
load more v
48%

Example: Program to demonstrate the creation of functional components. ,Example: We can also use a functional component into another component. The below program is to demonstrates the use of functional components in other components.,ReactJS Functional Components

Other "component-react" queries related to "React: cant get output inside a functional component"