Home > front end >  Why is a react element not updating?
Why is a react element not updating?

Time:07-03

I have a react component that takes the input from a materialUi text form and uses a useState hook to update. On submit I want it to update another variable to the value. This is being used in an h1 element. However, the h1 element is not updating. I know the variable is updating because I log it in the console and it updates.

import React, { useState } from 'react';
import CssBaseline from '@mui/material/CssBaseline';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import Alert from '@mui/material/Alert';
import { TextField } from '@mui/material';
import Button from '@mui/material/Button';
import './style.css';
import { useEffect } from 'react';


const darkTheme = createTheme({
    palette: {
      mode: 'dark',
    },
  });
export default function App() {

  const [myValue, setValue] = useState('') // The original hook
  let headingText = 'Hello World'
    let onSubmit = (e) => {
        e.preventDefault();
        headingText = myValue;
        console.log(headingText);
        console.log(myValue);
      
      };
    
  return (
    <>
    <title>Text Changer</title>
    <div className='joe'>
    <ThemeProvider theme={darkTheme}>
    <React.Fragment>
      <CssBaseline />
      <Alert severity="success">Page Loaded</Alert>
      <h1>{headingText}</h1> // the h1 I want to update
      <form onSubmit={onSubmit}>
      <TextField id="outlined-basic" label="Search Text" variant="outlined" value={myValue} onChange={(e) => setValue(e.target.value)}/>
      <br />
      <br />
      <Button variant="contained" color="primary" type="submit">Submit</Button>
      </form>
      
    </React.Fragment>
    </ThemeProvider>
    </div>
    </>
  );
  }

CodePudding user response:

You'll want to useState for that as well

const [headingText, setHeadingText] = useState('Hello World');
// ...
setHeadingText(myValue);

CodePudding user response:

You have to create a state as

  const [headingText, setHeadingText] = useState("Hello World");

CODESANDBOX DEMO.

and then onClick of a button you have to update state. React will re-render the component if the state changes

  let onSubmit = (e) => {
    e.preventDefault();
    setHeadingText(myValue);
  };
  • Related