Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Prompt rendering in Inquirer?

I am building a command line interface in node.js using library: inquirer.

based on my need I want to render prompt, confirmation text etc when user input's. example.

inquirer usage

var _questions = [{
  'type': 'list',
  'name': 'databasetype',
  'message': 'Choose database :',
  'choices': ['mongoDB', 'mysql [alpha]', 'firebase [alpha]', 'url [alpha]'],
  'default': 'mongoDB'
}, {
 'type': 'input',
 'name': 'xfactor',
 'message': 'X Factor [email, username etc..] :'
}]

// show question's.
Inquirer.prompt(_questions).then(async (__answers) => {
 console.log(__answers)
})

what i want

if user chooses mongoDB than it should render another prompt asking mongodb url

like image 498
Manu Yadav Avatar asked Jun 02 '19 05:06

Manu Yadav


1 Answers

You can use the when question property, its value should be a function that returns a boolean; true for show question, false for don't show question

so using your example:

_questions = [{
    type: 'list',
    name: 'databasetype',
    message: 'Choose database :',
    choices: ['mongoDB', 'mysql [alpha]', 'firebase [alpha]', 'url [alpha]'],
    default: 'mongoDB'
}, {
   type: 'input',
   name: 'url',
   message: 'Enter the URL',
   when: (answers) => answers.databasetype === 'mongoDB'
}]

see more examples here when usage examples

like image 97
Boswell Gathu Avatar answered Nov 08 '22 22:11

Boswell Gathu