- Forums
- react
- React: Differences Between Importing A Component And A Function
this page shows the comparison between a component and a function in react and how to use it [5314], Last Updated: Mon Jun 24, 2024
edw
Fri Apr 26, 2024
0 Comments
198 Visits
I used to get confused on how to use a component and function and because I didn't understand, i would get a bunch of errors. Hopefully, with these notes, I won't make too many errors.
As Component
- Pass props <Example value={thisvalue}>
- No curly brackets when importing
- use the <Example> to call the component
- Use export default
- you can use hooks like useState, useEffect
- You cannot pass state: For example <Example myState={myState}> - The state will not work in the component
App.jsx:
import GenerateField from "../../components/utilities/GenerateField"
<GenerateField setuploadFiles = {setuploadFiles} />
GenerateFields.jsx:
function GenerateField (props) {
let setuploadFiles = props.setuploadFiles;
setuploadFiles = setuploadFiles + 1; // do something
return (<>{setuploadFiles}</>)
}
export default GenerateField
As Function
- Pass parameters, not props {Example(thisvalue)}
- Yes curly brackets when importing
- use the Example(param) to call the component
- export function (no default needed)
- you can NOT use hooks like useState, useEffect inside the function
- You can pass state. For example <Example myState={myState}> - The state will update in the parent component that called the function
App.jsx
import {GenerateField} from "../../components/utilities/GenerateField"
return (
{GenerateField(message)}
)
GenerateFields.jsx
export function GenerateField (message) {
return (
<h1>{message} </h1>
)
}