I've moved all my static text to the constants file and I've to pass user's first name and last name to one particular key. I've tried using string literal but its not working. Is there any way to pass the values from react to the constants file.
constants.js
export constants={
'employeeName': `Hello welcome ${employee.firstname}, ${employee.lastname}`
}
React component
import constants from './constants.js'
const employee={
firstname:props.firstname,
lastname: props.lasname
}
<div>{constants.employeeName}</div>
CodePudding user response:
You can create a method and pass an argument on that.
Example :
const getFullName = (employee) => {
return {
'employeeName': `Hello welcome ${employee.firstname}, ${employee.lastname}`
}
};
const employee = {
firstname: "asif",
lastname: "vora"
};
const { employeeName } = getFullName(employee);
console.log(employeeName);
CodePudding user response:
If you insist to use a string constants in separate file and use and format it in another component you can use the parse method from this post or some string format library like hydrate-text like this:
constants.js
export const constants = {
employeeName: `Hello welcome %s, %s`,
};
util.js;
export function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, () => args[i ]);
}
component:
import { parse } from "util";
import constants from "./constants.js";
const Employee = () => {
const employee = {
firstname: props.firstname,
lastname: props.lasname,
};
return (
<div>
{parse(
constants.employeeName,
employee.firstname,
employee.lastname
)}
</div>
);
};
In my opinion it's not a clean and performant way of doing this, you can just use a function and pass employee to it like the other answers:
CodePudding user response:
constant.js:
export const constants= { employeeName: 'Hello welcome'}
React Component:
import constants from './constants.js'
const employee={firstname:props.firstname,lastname: props.lasname}
<div>{`${constants.employeeName} ${employee.firstname}, ${employee.firstname}`}</div>