Is it possible to use type submit event as component in a multipage web application

I will start by explaining my folder structure to understand the problem I Have.
Folder Structure:

app
 |--Todo
     |--page.tsx //where todo(s) will be created
 |--layout.tsx //global layout
 |--page.tsx //Main page were todo(s) will be viewed
components
 |--button.tsx //shared component that will be used throughout the whole app.
 |--header.tsx //header component

The button component is as follows: button.tsx

export default function Button(props:any){
  return <input type={props.submit} value={props.value} />
}

The header component is as follows: header.tsx

export default function Header(props:any){
  return <div>{props.children}</div>
}

Then the todo Page: àpp/todo/page.tsx

export default function TodoPage(){

const [todo, setTodo] = useState("");

 function saveTodo(){
   console.log(todo);
 }
 
 function todoHandler(e:any){
  const value = e.target.value;

  setTodo(value);
}

 return (
  <form onSubmit={saveTodo}>
   <div >
     <input type="text" placeholder="Todo Title" value={todoHandler} />
   </div>
  </form>
 )
}

Now the important part is the layout page, I’m going to share the layout with different page routes. I had the following in mind:

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Header>
          <h1>New Todo</h1>
          <Button value={"Save Todo"} />
        </Header>
        {children} //The rest of the page routes will render here.
      </body>
    </html>
  );
}

Conclusion, what I’m trying to achieve is to use the Headercomponent as a global view with the Button component in it. I will have multiple routes in the future and didn’t want to import the same button on every new page.

When I ran the above result and check my console, nothing is happening. However when I import and using the Button component within the todo/page.tsx file it works flawlessly. I wanted to find out if i’m missing something or is it impossible to use the above method which i want to try.

Here’s a diagram that I’ve included to help you understand what I’m trying to achieve:
Example Diagram

>Solution :

Give an id to your form

<form id="todo" onSubmit={saveTodo}>
  <div >
   <input type="text" placeholder="Todo Title" value={todoHandler} />
  </div>
</form>

Then target it with the "form" attribute on your input

export default function Button(props:any){
  return <input type={props.submit} value={props.value} form="todo" />
}

You may want to pass a "form" prop and change it depending on your current form of course

Leave a Reply