0

I am trying to render profile icons with a single letter on the condition of the users first letter of their first name.

EX: sam = 'S'

I have created a const for each letter and would like to render them but I'm not sure how to apply the letter variable to the component.

Here is what my code is looking like.

function foo() {
var obj = JSON.parse(localStorage.getItem('user'));
let firstName = obj[0].firstName;
let letter = firstName.charAt(0).toUpperCase();
render ( <S /> )
}

const S = () =>
<span className="profile-icons" style={{'backgroundPosition': '0 -576px',}} />
...
A-Z
2
  • Separate constants for each letter is the wrong way to do things. Make an object, with the keys being the letters and the value for each key being the function you want. Commented May 16, 2022 at 17:42
  • Give it a prop: reactjs.org/docs/components-and-props.html Commented May 16, 2022 at 17:48

1 Answer 1

2

You can simply implement it with props. Just be sure to give it a right styles.

const ProfileIcon = ({ letter }) => {
  return (
    <span className="profile-icons" style={{'backgroundPosition': '0 -576px',}}>
      {letter}
    </span>
  );
}
render (<ProfileIcon letter={letter} />)

reactjs.org/docs/components-and-props.html

Sign up to request clarification or add additional context in comments.

4 Comments

You are correct that this does show the S icon with the letter, however, it isn't exactly what I was looking for. I have constants like A,B,C,...Z and I want to match each constant with the string value of letter. So if letter = a, then <A /> is rendered. I don't believe this is possible with props?
then you would need an object map like const letterMap = { A: <A />, B: <B />, ... }; render(letterMap[letter]); if i understand it correctly.
I realize now that I was trying to solve the wrong problem. It wasn't smart to be using images to store the letters when I can use your suggested method and eliminate a lot of unnecessary code. Thanks (:
I thought you would have an unusual constraints that you should do it as above code. Glad that you finally got it. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.