skip to Main Content

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

this is the error

2

Answers


  1. Since you are using a functional component, accessing props from it is done by using the parameter of the function.

    function SectionInput(props)  {
    
        const {label} = props;
        return (<div>
            <form>
                {label && <label>{label}</label>}
                <input type="text" props />
            </form>
        </div>
        );
    }
    

    What you are doing is: Accessing the props from this that does not have it. Accessing it with this.props can be done with class components.

    Login or Signup to reply.
  2. 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

    function SectionInput(props) {
        const { label } = props;
        return (
            <div>
                <form>
                    {label && <label>{label}</label>}
                    <input type="text" {...props} />
                </form>
            </div>
        );
    }
    

    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

    <SectionInput label="Name" />
    

    This will render the SectionInput component with the label "Name" displayed above the input field.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search