回到terminal輸入
npm install react-router-dom@^6.2.1
然後在components建立Header.js
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => {
return (
<div className="flex pa1 justify-between nowrap orange">
<div className="flex flex-fixed black">
<Link to="/" className="no-underline black">
<div className="fw7 mr1">Hacker News</div>
</Link>
<Link to="/" className="ml1 no-underline black">
new
</Link>
<div className="ml1">|</div>
<Link
to="/create"
className="ml1 no-underline black"
>
submit
</Link>
</div>
</div>
);
};
export default Header;
修改App.js讓畫面呈現link
import React from 'react';
import CreateLink from './CreateLink';
import Header from './Header';
import LinkList from './LinkList';
import { Route, Routes } from 'react-router-dom';
const App = () => {
return (
<div className="center w85">
<Header />
<div className="ph3 pv1 background-gray">
<Routes>
<Route path="/" element={<LinkList/>} />
<Route
path="/create"
element={<CreateLink/>}
/>
</Routes>
</div>
</div>
);
};
export default App;
將react-router加入index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/index.css';
import App from './components/App';
import { BrowserRouter } from 'react-router-dom';
// 1
import {
ApolloProvider,
ApolloClient,
createHttpLink,
InMemoryCache
} from '@apollo/client';
// 2
const httpLink = createHttpLink({
uri: 'http://localhost:4000'
});
// 3
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
// 4
ReactDOM.render(
<BrowserRouter>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</BrowserRouter>,
document.getElementById('root')
);
修改CreateLink.js,讓submit完之後導回首頁
import React, { useState } from 'react';
import { useMutation, gql } from '@apollo/client';
import { useNavigate } from 'react-router-dom';
const CREATE_LINK_MUTATION = gql`
mutation PostMutation(
$description: String!
$url: String!
) {
post(description: $description, url: $url) {
id
createdAt
url
description
}
}
`;
const CreateLink = () => {
const [formState, setFormState] = useState({
description: '',
url: ''
});
const navigate = useNavigate();
const [createLink] = useMutation(CREATE_LINK_MUTATION, {
variables: {
description: formState.description,
url: formState.url
},
// 導回首頁
onCompleted: () => navigate('/')
});
return (
<div>
<form
onSubmit={(e) => {
e.preventDefault();
createLink();
}}
>
<div className="flex flex-column mt3">
<input
className="mb2"
value={formState.description}
onChange={(e) =>
setFormState({
...formState,
description: e.target.value
})
}
type="text"
placeholder="A description for the link"
/>
<input
className="mb2"
value={formState.url}
onChange={(e) =>
setFormState({
...formState,
url: e.target.value
})
}
type="text"
placeholder="The URL for the link"
/>
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default CreateLink;