Pavindu
Pavindu

Reputation: 3112

NextJS: Use same component in multiple routes for multiple pages

In my NextJS app, I have a search bar component OrderSearchBar.js and I want to use it in both index.js and /purchases.js pages but with different endpoints.For example,if I click search button on the index.js page,it should post form content to /orders and on the /purchases.js, form content should post to /purchaseDetails.Is there any way to accomplish this?

File Structure

OrderSearchBar.js

class OrderSearchBar extends Component{
constructor(props) {
    super(props);
    this.onChangeInput = this.onChangeInput.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    this.state = {
        nature: '',
        type: '',
        searchBy: '',
        startDate: '',
        endDate: '',
        keyword: ''
    }
}

onChangeInput(e) {

    this.setState({
        [e.target.name]: e.target.value
    });
}

onSubmit(e) {
    e.preventDefault();
    const t = {
        nature: this.state.nature,
        type: this.state.type,
        searchBy: this.state.searchBy,
        startDate: this.state.startDate,
        endDate: this.state.endDate,
        keyword: this.state.keyword
    }
    axios.post('/search', t)..then(res => console.log(res.data));
    /*I can do this for single endpoint.but how do I add multiple endpoints 
    for use in different pages?*/


    this.setState({
        nature: '',
        type: '',
        searchBy: '',
        startDate: '',
        endDate: '',
        keyword: ''         
    });
}

Upvotes: 0

Views: 4381

Answers (2)

FooBar
FooBar

Reputation: 6108

While you could use window property, this might not work if you're using Nuxt.js or other server side rendering, since the window object is not present.

Instead, I suggest you pass a prop down to your component, say:

<component :type="'isPurchaseDetails'">

or for purchases

<component :type="'isPurchases'">

Upvotes: 1

Darryl RN
Darryl RN

Reputation: 8228

You can differentiate the current location in your orderSearchBar.js by getting the pathname of window.location object.

onSubmit(e) {
    e.preventDefault();
    const t = {
        nature: this.state.nature,
        type: this.state.type,
        searchBy: this.state.searchBy,
        startDate: this.state.startDate,
        endDate: this.state.endDate,
        keyword: this.state.keyword
    }
    const pathName = window && window.location.pathname;
    const destination = (pathName === '/purchases') ? '/purchaseDetails' : '/orders'
    axios.post(destination, t)..then(res => console.log(res.data));

    this.setState({
        nature: '',
        type: '',
        searchBy: '',
        startDate: '',
        endDate: '',
        keyword: ''         
    });
}

Upvotes: 3

Related Questions