How to addressing dynamic image path in react

Hello

For loading a dynamic image I should give a path. How should I give the path dynamically?

const currentImage = React.UseContext(ImageContext);
return (
        <ImageContext.Consumer>
       
            <ImageEditor
                includeUI={{
                    loadImage: {
                        path: imageSrc,
                        name: "image",
                    },
         
        </ImageContext.Consumer>
    );

You can see here:

loadImage: {
        path: 'img/sampleImage.jpg',
        name: 'SampleImage'
      },

thanks,

Saeed

Your code should include the context provided in the JSX template. Also depends on what your context looks like.
I.e.:

<ImageContext.Consumer>
{context=>(
<ImageEditor
                includeUI={{
                    loadImage: {
                        path: context.path,
                        name: "image",
                    },
         }
)
</ImageContext.Consumer>

I encounter this error:

/src/App.jsModule not found: Can't resolve './components/ImageUpload1' in 'H:\react_Image_Editor_TRY\imageEditor19\ClientApp\src'

Is this line Incorrect:

const currentImage = React.UseContext(ImageContext);

and in the loadImage what should I name the image?
just “image” or “currentImage”?

I mean this line:

includeUI={{
                    loadImage: {
                        path: context.path,
                        name: "image",
                    },

I can see the error but need to see the source code of this page and perhaps the context as well. React hooks follow camel case React.useContext(ImageContext).
The name of the image is up to you and how u want to use it. If u want to hardcode it "image" that’s ok, but you might want to set it dynamically as well so I’d recommend assigning value from context.

As @doubleUTF , it is useContext, not UseContext.

And you have a syntax error

<ImageEditor
                includeUI={{
                    loadImage: {
                        path: imageSrc,
                        name: "image",
                    }
         }

The component is missing closing slash and angle brackets.

And it is either

const currentImage = React.useContext(ImageContext);

return (
  <ImageEditor includeUI={{ ...stuff }} />
)

OR

<ImageContext.Consumer>
  {({stuff}) => (
    <ImageEditor includeUI={{ ...stuff }} />
  )}
</ImageContext.Consumer>

It’s impossible to see what the issue is though, as you’re not providing enough code to see where the issue is – we can’t see if you’re using some library, or if you’ve written code for the context somewhere else, or whatever. I think there are more errors w/r/t to what you’re writing, but need more info

You can see here:

ImageContext.js

import React from 'react';
const ImageContext = React.CreateContext('null');
export default ImageContext;

ImageUpload.js

return (
            **<ImageContext.provider value={this.state.selectedFile.name}>**
            <div>
                <div style={mystyle} onClick={this.onNavToEditor}/>
                <h1>File Upload Demo</h1>
                <div >{this.state.uploadResult} onClick={this.onNavToEditor}</div>
                <div>
                    <input type="file" onChange={this.onFileChange} />
                    <input type="text" value={this.state.value} onChange={this.onDescriptionChange} />
                    <button onClick={this.onFileUpload}>
                        Upload!
                    </button>
                 
                </div>

                {this.listItems()}
               
                </div>
            </ImageContext.provider>
        );

ImageEditor.js

return (
        <ImageContext.Consumer>
            {context => (
        <div className="home-page">
            <div className="center">
                <h1>Photo Editor</h1>
                <Button className='button' onClick={saveImageToDisk}>Save Image to Disk</Button>
                </div>
                
                    <ImageEditor
                        includeUI={{
                            loadImage: {
                                path: context.path,
                                name: "image",
                            },
                            theme: myTheme,
                            menu: ["crop", "flip", "rotate", "draw", "shape", "text", "filter"],
                            initMenu: "",
                            uiSize: {
                                height: `calc(100vh - 160px)`,
                            },
                            menuBarPosition: "bottom",
                        }}
                        cssMaxHeight={window.innerHeight}
                        cssMaxWidth={window.innerWidth}
                        selectionStyle={{
                            cornerSize: 20,
                            rotatingPointOffset: 70,
                        }}
                        usageStatistics={true}
                        ref={imageEditor}
                    />
               
                </div>
            )}
        </ImageContext.Consumer>
    );

I can send you more code if you need it.

value={this.state.selectedFile.name}

value has to be an object, whereas this is (I assume) a string. value is literally the context, it’s the thing you access. Like you’re trying to access context.path but that property doesn’t exist, you haven’t defined it.

As you can see the code please let me know your idea.

value has to be an object, whereas this is (I assume) a string. value is literally the context, it’s the thing you access. Like you’re trying to access context.path but that property doesn’t exist, you haven’t defined it.

As you can see here the context takes a value here:

ImageUpload.js

//import axios from 'axios';
import React, { Component } from 'react';
import { Redirect } from "react-router-dom";
import ImageContext from '../ImageContext';


//import React, { useState } from 'react';


export default class ImageUpload extends Component {
    static displayName = ImageUpload.name;

    constructor(props) {
        super(props);
        this.state = {
            redirect: null,
            selectedFile: null,
            description: null,
            uploadResult: null,
            fileIdList: []
           
        };

        this.onNavToEditor = this.onNavToEditor.bind(this);
    }

    getList = () => {
        fetch('api/Image')
            .then(response => response.json())
            .then(data => this.setState({ fileIdList: data }));
    };

    componentDidMount() {
        this.getList();
    };

    onFileChange = event => {
        this.setState({ selectedFile: event.target.files[0] });
    };
    onDescriptionChange = event => {
        this.setState({ description: event.target.value })
    };
    onFileUpload = async () => {

        const formData = new FormData();

        formData.append(
            "ImageData.File",
            this.state.selectedFile,
            this.state.selectedFile.name
        );


        //try {

        fetch('/api/Image', {
            method: 'POST',
            body: formData
        }).then(resposne => resposne.json())
            .then(data => {
                console.log(data);
                this.setState({ uploadResult: "File " + data.fileName + " successfully uploaded." });
                this.getList();
            });
        //console.log(res);

        //} catch (ex) {
        //    console.log(ex);
        //}
    };


    onNavToEditor = async () => {

        //this.props.history.push
        //history.pu
        this.setState({ redirect: "/ImageEditor" });
      
        
    };

    //try {
    //    const res = await axios.post("Image/Image/Post", formData)
    //    console.log(res);

    //} catch (ex) {
    //    console.log(ex);
    //}
//};
 

    listItems = () => {
        const listItems = this.state.fileIdList.map((item) =>
            <div key={item.imageId.toString()}>
                <img src={"/api/Image/DownloadImage/" + item.imageId}
                    alt={item.fileName}
                    className="img-thumbnail"
                    height="100" width="100" />
            </div>
        );
        return (<div>{listItems}</div>);
    };

    render() {
        if (this.state.redirect) {
            return <Redirect to={this.state.redirect} />
        };
        const mystyle = {
            
            backgroundColor: "DodgerBlue",
            margin: "100px",
           
            height: "100px",
            width:"100px"

            
        };

        return (
            <ImageContext.provider value={this.state.selectedFile.name}>
            <div>
                <div style={mystyle} onClick={this.onNavToEditor}/>
                <h1>File Upload Demo</h1>
                <div >{this.state.uploadResult} onClick={this.onNavToEditor}</div>
                <div>
                    <input type="file" onChange={this.onFileChange} />
                    <input type="text" value={this.state.value} onChange={this.onDescriptionChange} />
                    <button onClick={this.onFileUpload}>
                        Upload!
                    </button>
                 
                </div>

                {this.listItems()}
               
                </div>
            </ImageContext.provider>
        );
    }
}

Can you see something wrong here?

What is this.state.selectedFile.name

The name of the file is chosen for upload.

I recommend using a linter like ESLint or TSLint to solve all the syntactical errors. Might want to even add Typescript for React to solve the typing errors, they will show up when you’re not passing the right stuff.

So again, to repeat value has to be an object. Objects in JavaScript are like

{
  name: "some string"
}

Not

{
  "Some string"
}

But my project is based on Microsoft react/ASP.net Core template.

Can you see any error in the code?

You mean ImageContext provider part?

Yes, the context provider takes a single prop, value. That is always an object: the point of a context is that you can access that object anywhere further down the tree.

This does not mean you can’t install a linter plugin in VS if that’s what you’re using

You mean which changes should I make? or how I share the state between components?

If that value is a string, then the provider code is wrong. In the consumer you are trying to access context.somePropertyOfTheValueObject and because value isn’t an object, there is nothing to access, it won’t work. You have to write like Provider value={{ property: "an object property" }}>, the thing that has to go here: value={HERE} has to be object, that’s the value of the context

There seem to be other basic syntactic errors here, which is why you’re being advised to lint the code, ie install a plugin in your IDE that highlights errors

If you are just adjusting a template here and you don’t really understand what it is you’re doing, the code is complex and so I would write a few small examples first, following the React docs, so that you understand what you’re doing.