The Condor The Condor - 28 days ago 20
Javascript Question

How to pass dynamic params in URLs

I am following a tutorial of React, everything works except for this part:

let teacherTopic = event.target.elements[0].value;
let teacherName = event.target.elements[1].value;
let path = 'featured/${teacherTopic}/${teacherName}';
browserHistory.push(path);


I tried to log on the console the values of the first two variables, and I get the actual value. However, when I construct the path the values passed are actually ${varName}, not the value contained in them.

What am I doing wrong? Thanks!

Answer

ES6 template literals use (`) instead of regular quotes. If you need to nest javaScript variables in your strings, wrap them in backticks.

You example would be:

let teacherTopic = event.target.elements[0].value;
let teacherName = event.target.elements[1].value;
let path = `featured/${teacherTopic}/${teacherName}`;
browserHistory.push(path);

Read more about template literals here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals

Comments