I have this kind of Router component:
import addProduct from "../components/Products"
[...]
<BrowserRouter>
<div className="content">
<Switch>
<Route path="/products">
<Products />
</Route>
<Route path="/add">
<AddProduct onSubmit={addProduct} />
<Products />
</Route>
</Switch>
</div>
</BrowserRouter>
Products, which look like this (I only paste the most important things):
const addProduct = async (newProduct) => {
const response = await axios.post('https://fakestoreapi.com/products', newProduct);
console.log(response)
setProducts([...products,response.data])
}
[...]
inside return I have a link to form, where we can create a new product:
<NavLink to="/add">
<h2>Click me to add a new product</h2>
</NavLink>
The problem is that before I started making react-router-dom, my component <AddProduct /> was inside the Products and that I could pass the addProduct function to AddProduct immedietaly, so I was making <AddProduct onSubmit={addProduct}/>.
At the moment I don't know what I should do to pass my addProduct function to <AddProduct> component when it's not inside Products now.
AddProduct looks like this if it matters in this case:
import ProductsForm from './ProductsForm'
function AddProduct({onSubmit}) {
return (
<ProductsForm onSubmit={onSubmit} initialValues={{title: '', price: '', category: '', image: ''}} />
)
}
export default AddProduct;
It looks like you may benefit from a state management system. There are a few around, including redux & mobx. You could also 'roll your own' using react's in-built Context API. This allows you to store your state in one location, and have only the components that need it subscribe to the store for data or functions to modify that data.
If this is only for a small app, you can get away with using Context (plus it's a great tool in your belt!). It's not so good for larger apps as it has only been designed to manage small kinds of data