react-hook-form: how to show errors for nested names?

Viewed 713

I have a register("test.new",{required:true}) in react-hook-form

Now how to show errors of test.new

{errors.test.new && <p style={{ color: "yellow" }}>This field is required</p>}

is not working

1 Answers

Before you enter anything, there is no error, so the errors object doesn't have any property, you need to add an optional chaining operator to safely get the nested property inside in case it's undefined:

{errors.test?.new && (
  <p style={{ color: 'red' }}>This field is required</p>
)}

Live Demo

Codesandbox Demo

Related