Having difficulty showing an image in the navigation provided via useContext()

The image is successfully displaying in the Profile.js screen and other areas. However, when attempting to pass the image via useContext() to display in Navigation.js, it shows as src(unknown). What could be causing this issue?

https://i.stack.imgur.com/wxb7X.png Profile.js

const {picture, setPicture} = useContext(UserProfileContext);
const [updateProfile, setUpdateProfile] = useState({ _id: '', photo: '', name: '', email:'', phonenumber:'', position:'', privilege:'', password:''});

     const onChangePicture = e => {
        if (e.target.files.length) {
          setPreview(URL.createObjectURL(e.target.files[0]));
          setPicture(e.target.files[0]);
        } else {
          return false;
        }
      };


      const handleChange = (e, id) => {
        e.persist();
        let itemIndex;
        const targetPlayer = playerProfile.find((player, index) => {
          console.log({ player, id, index });
          itemIndex = index; 
          return player.id === id;
        });
        console.log({ targetPlayer, id, e });
        const editedTarget = {
          ...targetPlayer,
          [e.target.name]: e.target.value
        };
        const tempPlayers = Array.from(playerProfile);
        tempPlayers[itemIndex] = editedTarget;
        setPlayerProfile(tempPlayers);
        setUpdateProfile({ ...updateProfile, [e.target.name]: e.target.value }); // this is added just to see if its working
        setProfile({ ...profile, [e.target.name]: e.target.value });
        setPicture(e.target.files[0]);
      };

    <div className="formInstructionsDiv formElement">
            <div className="register_profile_image">
                 <input id="profilePic" name="photo" type="file" onChange={onChangePicture} />
            </div>
            <div className="previewProfilePic" >
                 <img alt="" onError={addDefaultSrc} name="previewImage" className="playerProfilePic_home_tile" src={photo} onChange={e => handleChange(e, id)}></img>
            </div>
    </div>

UserProfileProvider.js

import UserProfileContext from '../context';

const UserProfileProvider = ({children}) => {

    const [picture, setPicture] = useState({ photo: ''});


     const value = useMemo(() => ({
        picture, setPicture
    }), [picture]);


    return (
       <UserProfileContext.Provider value={value}>
           {children}
       </UserProfileContext.Provider>
    )   
}
export default UserProfileProvider;

Navigation.js

const Navigation = () => {

    const {picture} = useContext(UserProfileContext); 

    return localStorage.getItem('loginEmail') &&
        <div className="App">
            <div className="wrapper">
                <div id="wrap">
                    <nav className="siteNavigation_nav_links">
                    <div className="clubLogo landing"style={divStyle}><b>Southside Soccer</b></div>
                        <NavLink className="mobile_register_link" to="/">Home</NavLink>
                        <NavLink className="mobile_register_link" to="/profile">Profile</NavLink>
                        <NavLink className="mobile_login_link" to="/login" onClick={logout}>Logout</NavLink>
                        <NavLink className="mobile_login_link" to='/aboutus'>About us</NavLink>
                        <span className="mobile_login_link"><img className="nav_profile"src={picture.photo}></img></span>
                    </nav>
                </div>
            </div>
        </div>
}

export default Navigation;

Answer №1

It is important to note that the picture object in your state declaration should be an empty string:

const [picture, setPicture] = useState({ photo: ''});

However, when you update it, you are setting the file object directly into it using setPicture(e.target.files[0]);, which results in picture.photo being undefined.

Additionally, you cannot render an image directly from a File object; you need to use FileReader to convert it into a data blob.

const onChangePicture = e => {
    if (e.target.files.length) {
      setPreview(URL.createObjectURL(e.target.files[0]));
      setPicture({photo:e.target.files[0]});
    } else {
      return false;
    }
  };

In Navigation, you will need to use it like this:

const Navigation = () => {
    const [imageSrc, setImgSrc] = useState(null);
    const {picture} = useContext(UserProfileContext); 

    useEffect(() => {
       const reader = new FileReader();
       reader.addEventListener('load', () => {
           setImgSrc(reader.result);
       });
       reader.readAsDataURL(picture.photo);
    }, [picture.photo])
    return localStorage.getItem('loginEmail') &&
        <div className="App">
            <div className="wrapper">
                <div id="wrap">
                    <nav className="siteNavigation_nav_links">
                    <div className="clubLogo landing"style={divStyle}><b>Southside Soccer</b></div>
                        <NavLink className="mobile_register_link" to="/">Home</NavLink>
                        <NavLink className="mobile_register_link" to="/profile">Profile</NavLink>
                        <NavLink className="mobile_login_link" to="/login" onClick={logout}>Logout</NavLink>
                        <NavLink className="mobile_login_link" to='/aboutus'>About us</NavLink>
                        <span className="mobile_login_link"><img className="nav_profile"src={imageSrc}></img></span>
                    </nav>
                </div>
            </div>
        </div>
}

export default Navigation;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass a div element and a variable from a Child component back to a Parent component in Next.js/React?

My goal is to create a webapp that, when an item in the list generated by the child component is clicked, displays the corresponding image in a div within the parent component. After some trial and error, I managed to generate the list in the child compone ...

What could be causing the error "Hydration failed" in Devtools when starting a project with Remix's Indie stack?

During my exploration of Remix, I followed a tutorial to set up a project. However, upon inspecting Devtools, I was surprised to find several errors in the console. Warning: Unexpected <div> found in <html> within server-rendered HTML. Er ...

Arrange the grid in a pleasing manner

I'm really struggling with this issue. In my current setup, I have a Grid container that holds two separate grids - one for a textfield and another for a checkbox. Unfortunately, I can't seem to get them to align properly. <Grid container& ...

Modifying arrays in ReactJS

Having trouble editing my array list, need some help. I can update a single input value successfully, but struggling with updating the entire array. Any suggestions on why the method isn't working and how to edit the array? When I try to store data ...

The mock function will only be triggered if it is placed at the beginning of the file

In an attempt to simulate a React function component for the purpose of validating the properties passed to it, I encountered an interesting difference in behavior. When the mock is placed at the top of the file, everything works as expected: const mockTra ...

Utilizing Node.js with AWS CodeDeploy

I just finished developing an application with Express and Node.js. It runs smoothly on my local environment. Now I'm trying to figure out how to deploy it and run the server on CodeDeploy. Should I make any modifications to the appsec? ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

The connection between AngularJS and the Node.js server is struggling with sending input data, resulting in a 404 error message

Why is the HTTP address not found? I am seeing these mistakes in the console: POST http://localhost:3000/api/message 404 (Not Found) angular.min.js XHR finished loading: POST "http://localhost:3000/api/message". angular.min.js Error " ...

React - Dynamically import file path for PDF document

Initially, the page will send an http request to an API The API will then respond with an object containing a path: ./assets/sample.pdf I am trying to extract the urlPdf from import urlPdf from response.path Any suggestions on how I can achieve this? ...

The importance of context visibility for functions in JavaScript within a React.js environment

Why is it that the react state is visible in the function handleFinishChange, but cannot be seen in validationFinishTime? Both are passed to the component InputFieldForm. When executing this code, an error of Uncaught TypeError: Cannot read property ' ...

Guide to applying conditional styling to Material-UI TextField

After creating a custom MUI TextField, I implemented the following styling: const CustomDisableInput = styled(TextField)(() => ({ ".MuiInputBase-input.Mui-disabled": { WebkitTextFillColor: "#000", color: "#00 ...

What is the best way to centrally align a Card while keeping the text left-aligned?

New to coding and need some guidance. I'm attempting to create a card that is not the full width of the window. I have specified a cardStyle as shown below. cardStyle:{ width: '95vw' align? : 'center?' textAlign? : &a ...

When using Axios to GET from a local PHP file, it only retrieves the code instead of running

I've run into an issue accessing the API as it has CORS disabled, requiring me to make requests on the server side. Currently, I'm using React and Axios to send a GET request to a local php file that should trigger cURL execution. However, instea ...

Issues with React Router functionality on a live production site are causing complications

I recently created an Amazon-clone UI using create-react-app, but it only displays dummy data. The issue arises after deploying it to Vercel - the routing does not function as expected. When clicking on links, a blank page appears with correct URL paramete ...

Adjusting the zoom feature in CSS3

I'm looking to have my React app display as if the user has changed the zoom level to 90%. I attempted to tackle this issue using CSS. body { transform: scale(0.9); } However, this method did not result in the screen appearing similar to wh ...

Apple browsers posing problem for React JS functionality

Having an issue with my React JS website loading on IOS devices. It works fine on Windows and Android, but nothing loads on iOS. I attempted to use in my index file without success. Unfortunately, I don't have a Mac for debugging and can only test on ...

Is it possible to customize the MUI CSS for a specific menu item using the sx prop?

How can I apply the MenuItemStyle to the sx prop of a MenuItem using: const MenuItemStyle = { '&:hover': { backgroundColor: `${theme.color.secondaryHover}`, }, '&:selected, &:selected:hover': { backgroundColor: ...

Styling material-ui components using emotion: A comprehensive guide

I am looking to customize the Material UI Tooltip component by applying styles to its tooltip and arrow classes. How can I achieve this using emotion? I attempted to follow a guide at https://github.com/mui-org/material-ui/issues/11467#issuecomment-423845 ...

There is no data in the request body when submitting form data

When attempting to send form data using a simple post request to my backend, I noticed that the body is always empty. To troubleshoot this issue, I modified the content type to application/json and changed the data to JSON format, which allowed me to succe ...