I have two components within App.js. The main App
component (that contains a basic form) and a custom TextInput
component. I understand that ideally, it would be better to have separate files. However, I am trying to keep this as brief and simple as possible.
Anyway, I declare a state variable with const [success, setSuccess] = useState(false);
within the first component and would like to use this within the second component. I tried declaring the variable outside of both components to enable sharing, but that didn't work. How should I go about doing this? I mean normally, I would just export and import, but here, both components are on the same page.
To share the state you need to declare the state in the parent component (App in your case) and send it to the child component (TextInput)
eg
function App() {
const [success, setSuccess] = useState(false);
...
return (
<TextInput success={success} setSuccess={setSuccess} />
);
}
function TextInput({success, setSuccess}) {
// use success/setSuccess from props
}
You will have to pass props from parent(App component) like :
function App() {
const [success, setSuccess] = useState(false);
return (
<TextInput success={success} />
);
}
and to access it in TextInput component
function TextInput(props) {
//Access it using props.success
}
In this case, if you have given a pascal case naming for the text input such as function TextInput(){...}
, then react will consider this as a separate component even if this is defined in the same file. This is why the state variables of the App
component are not within the scope of TextInput
You can mitigate this by following either of the following approcahes,
function textInput(){
// the state variable 'success' and 'setSuccess' will be normally accessible here
return(
<div>
<input type="text" />
<div>
)
}
//return for the 'App' component
return(
<>
{textInput()}
</>
)
Passing the state as props
to the TextInput
component
If you follow this approach, then you can have the TextInput
component in a separate file as well
//parent 'App' component
function App(){
const [success, setSuccess] = useState(false);
return(
<>
<TextInput success={success} setSuccess={setSuccess}></TextInput>
</>
)
}
function TextInput(props){
const {success, setSuccess} = props;
// In here you can refer success and setSuccess normally as you would even if this is in a separate file
}
Not sure if maybe I am misunderstanding but...
//App.js
function App() {
const [success, setSuccess] = useState(false);
return (
<TextInput success={success} />
<FormComponent success={success} />
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.