Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

75
Views
Passing values from react components to constants file

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>
7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

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:

7 months ago · Juan Pablo Isaza Report

0

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);

7 months ago · Juan Pablo Isaza Report

0

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>
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.