I am trying to get a attribute input for the label tag while rendering the component. Using props to do this but its giving the following error-
Cannot read properties of undefined (reading ‘props’)
TypeError: Cannot read properties of undefined (reading ‘props’)
function SectionInput() {
const {label} = this.props;
return (<div>
<form>
{label && <label>{label}</label>}
<input type="text" props />
</form>
</div>
);
}
the above is my component
<SectionInput label="Title"/>
This is how I’m using it
2
Answers
Since you are using a functional component, accessing props from it is done by using the parameter of the function.
What you are doing is: Accessing the
props
fromthis
that does not have it. Accessing it withthis.props
can be done with class components.In functional components in React, you don’t use this.props to access the props passed to the component.
Instead, you can directly access the props object as a parameter to the component function. Here’s the corrected code
In the code above, props is passed as a parameter to the SectionInput function component. Then, you can destructure the label prop from the props object.
To assign the remaining props to the input element, you can use the spread operator ({…props}).
This will pass all the props received by the SectionInput component to the input element.
Now, you can use the SectionInput component and pass the label prop as needed, for example
This will render the SectionInput component with the label "Name" displayed above the input field.