Set readOnly attribute for different page in React JS

533 Views Asked by At

I had 2 different files and combined it int one web page. At one.js file in contain the text input and at the second.js files I had confirm button. What I want is, the user filled the value in one.js files than click confirm button on second page, the text input will be read only.

one.js

<TextField
    type="text" 
    name={'jobs'}
    value=''
    fullWidth
/>

second.js

<Button
  variant="contained"
  disabled={!this.state.valid  || this.state.isDisabled }

  >
  Confirm
  </Button>

So far, I knew how to do it if using a single .js file. So is it possible to do this if have 2 different files?

Thanks for the clue

1

There are 1 best solutions below

0
ViktorG On

What you are talking about is essentially a shared state between components, which updates as soon as the Button component is pressed and defines the read-only property of the TextField component. You need to use the respective state approaches for class and functional components, since state changes need to trigger a rerender.

The state should be defined in an encapsulating parent component. A possible implementation, using functional components and hooks, can be found below:

Parent.jsx

import React from 'react';
import {TextFieldComponent} from 'one.js';
import {ConfirmButton} from 'two.js';
    
const Parent = () => {
  const [content, setContent] = React.useState("");
  const [isReadOnly, setIsReadOnly] = React.useState(false);

  return (
    <div>
      <TextFieldComponent 
        readOnly={isReadOnly}
        content={content}
        setContent={setContent}
      />
    
      <ConfirmButton 
        setIsReadOnly={setIsReadOnly}
      />
    </div>
  )
}

one.js (example without imports)

export const TextFieldComponent = ({content, setContent,isReadOnly}) => {
  return(
     <TextField
       type="text" 
       name={'jobs'}
       value={content}
       fullWidth
       readOnly={isReadOnly}
       onInput={text => setContent(text)}
     />
  )
}

two.js (example without imports)

export const ConfirmButton = ({setReadOnly}) => {
  return(
    <Button
      variant="contained"
      disabled={!this.state.valid  || this.state.isDisabled }
      onClick={() => setReadOnly(true)}
    >
      Confirm
    </Button>
  )
}

I would highly recommend reading the official documentation regarding state and lifecycle.