What I want: Create 2 page in Next.JS in React.JS that can do the following:
What I tried to do and I didn't successfully to do that
import Head from 'next/head'
import React, { Component } from 'react'
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import Link from 'next/link'
function submitForm() {
if(process.browser) {
alert(document.getElementById('subvalue').value)
}
}
export default class Home extends React.Component {
render() {
return (
<div className="container">
<Head>
<title>Reddit Feed App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<form action="#" onSubmit={this.handleSubmit}>
<label>Search for any subreddit :</label>
<input type="text" id="subvalue"/>
<span onClick={submitForm()} >Submit</span>
</form>
</main>
...
</div>
)
}
}
So, I'm stuck I'm blocked I already did not succeed to make my submit form function working. How to do it?
First you have to get the value of the input on submit and programatically changing the current route :
You can get the value by making a ref to the <input />
element:
Your first page should look like this /pages/index.js
import { useRouter } from "next/router";
import { useRef } from "react";
export default function IndexPage() {
const router = useRouter();
const inputRef = useRef(null);
const onSubmit = (e) => {
e.preventDefault();
// some validations here
router.push(`search/${inputRef.current.value}`);
};
return (
<form onSubmit={onSubmit}>
<input name="second_page" type="number" ref={inputRef} />
<button type="submit">submit</button>
</form>
);
}
This will get you to /search/[the value you submitted]
.
In order to create that dynamic page you should use the Dynamic API Routes .
Just create a file named /pages/[paramPassed].js
I made an example with the jsonplaceholder api:
export default function Search({ res }) {
return (
<div>
Here's the result :
<pre>
<code>{JSON.stringify(res)}</code>
</pre>
</div>
);
}
export async function getServerSideProps({ params }) {
const { paramPassed } = params;
const req = await fetch(
`https://jsonplaceholder.typicode.com/todos/${paramPassed}`
);
const res = await req.json();
return {
props: { res } // will be passed to the page component as props
};
}
The getServerSideProps
allows you to set default params to your page component before rendering it.
You can use the fetch API or SWR inside your React components for remote data fetching; or use Next.js' data fetching methods for initial data population.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.