How to pass image url as prop in React - reactjs

I have an image uri that i want to pass as prop so that i can load it when it when the component is rendered. as i will be changing images i cannot have a static uri. but i keep getting this error
Error: Cannot find module "."
although it does work when i statically load the images. Also i need to use the img element and not Image.
require('./cube.jpg')
here is my code
here is my parent class declaring the component:
<InputSection ref="inputS" ImD={this.getData} imageUri={this.state.imageurl} />
imageurl state is defined as:
imageurl: './cube.jpg',
child component:
return(
<div style={style}>
<br/>
<img ref="image" src={require(this.props.imageUri)} onLoad={this._onImageChanged.bind(this)} />
<canvas style={{display:'none'}}width={300} height={300} ref="inputCanvas" >
</canvas>
</div>
);

Did you try the other way around? I am assuming you will import the images in your parent component. Also the reason you are getting that error is probably because your Parent component and Child component are not in the same directory. The image path is ./cube relative to Parent which means it resides in the same directory as Parent.
Parent Component
<InputSection ref="inputS" ImD={this.getData} imageUri={require(this.state.imageurl)} />
Child Component
<img ref="image" src={this.props.imageUri} />

you can do this
<img src={require(${this.props.YourPropName})} alt="My Image"/>
and take any name as a prop in the tag and then pass it!!

Related

Alias inside require function in React

I want to use alias inside require function for dynamically load img src.
There is a list of image items in the component. So it's not possible to import and map all of them manually in src.
Whenever i am trying relative path, it's working.
<img src={require('../../assets/images/' + imageurl)} alt={title} />
But if i change this line to below one, it's breaking.
<img src={`require(#assets/images/${imageurl})`} alt={title} />
Note: I already setup my assets alias in the project.
Try this:
<img src={require(`#assets/images/${imageurl}`)} alt={title} />

how to pass props on the view to a redux connected react component?

i have a component called Paginate who recive states from redux and i want to pass a prop normaly on the view to change his comportament depends what page a called it, the props never shows up i alredy tryed pass the component to class and doenst work.
code here: https://codesandbox.io/s/paginate-redux-test-tqi5d
<Provider store={store}>
<div className="row text-center">
<Paginate mode="search" />
</div>
<div className="row text-center">
<Paginate mode="report" />
</div>
</Provider>
inside the view.js = undefined
console.log(props.mode);
Check this https://codesandbox.io/s/paginate-redux-test-694ev
Reason your passed props to Paginate component is not appearing is because you are using mergeProps while connecting the component. If so you have to explicitly pass the ownProps(3rd param of mergeProps function) to the returned object.
https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#mergeprops-stateprops-dispatchprops-ownprops--object

In vue-electron, how to do you bind data between a parent and child components?

I am trying to learn electron-vue by understanding a finished code.
For the source, I am using Eplee, which is an epub reader built with vue js + electron
Here is the source link to Eplee.
https://github.com/Janglee123/eplee
<!-- BookmarkMenu.vue -->
<template>
<el-popover :popper-class="`popper ${theme}`" width="350" trigger="hover">
<div class="el-popover__title">
Bookmarks
<el-button size="mini" icon="el-icon-plus" circle #click="addBookmark" />
</div>
<el-button slot="reference" size="small" icon="el-icon-collection-tag" circle />
<el-tree :data="bookmarks" node-key="id" #node-click="onNodeClick">
<span slot-scope="{ node }" class="custom-tree-node">
<span>{{ node.label }}</span>
<span>
<el-button type="text" icon="el-icon-close" #click="() => removeBookmark(node)" />
</span>
</span>
</el-tree>
</el-popover>
</template>
<script>
export default {
name: 'BookmarkMenu',
props:{
bookmarks:{
default:()=>{},
type: Array,
},
theme:{
default:'default',
type:String,
}
},
methods:{
addBookmark(){
this.$emit('add-bookmark');
},
removeBookmark(data){
this.$emit('remove-bookmark',data);
},
onNodeClick(data){
this.$emit('node-click',data);
}
}
}
</script>
<style lang="scss" scoped>
</style>
I do not understand how data is binded here.
For example,
<el-button size="mini" icon="el-icon-plus" circle #click="addBookmark" />
when there is a click
it triggers addBookmark method of BookmarkMenu.vue
addBookmark Method triggers 'add-bookmark' of the parent component
But, <el-button></el-button> is just a class added for the purpose of styling, not a parent component.
For both vue and react, I thought in order to import components from a different file and properly place them I need to place two things.
import line
placement line
Question 1:
Is this a proper way to import? or do you only need 1. import line?
Question 2:
So, in vue-electron, how to do you bind data between a parent and child components?
What I am assuming is the file structor take cares of it
https://github.com/SimulatedGREG/electron-vue/blob/master/docs/en/renderer-process.md
Electron is just a runtime for your web app.
Take a look at Vue.js's event model.
https://v2.vuejs.org/v2/guide/events.html
https://v2.vuejs.org/v2/guide/components-custom-events.html
Also, check out component guide https://ru.vuejs.org/v2/guide/components.html
In your case
<el-button></el-button> is just a class added for the purpose of styling, not a parent component.
It is not a parent component it is a child component of <BookmarkMenu> component. And it may contain absolutely anything inside.
And this.$emit('add-bookmark'); method triggers an event listener (if any) of a component which would have <BookmarkMenu> as a child.
For example <BookmarkMenu #add-bookmark="someHandlerInAComponentContainingBookmarkMenu"/>

Passing components into another in react

I have an app with a number of components. One of the components I need be to able to pass different variations of another two components into, based on a layout. I believe it can be passed in like a data attribute, but I'm unsure of the exact syntax to push the other components in.
Given two components <List /> and <Box /> which are currently in another component being imported into my main App.js file as such:
export const CallOut = () => {
return(
<div style={styles.sectionInner}>
<List />
<BoxRight/>
</div>
)
};
where <CallOut /> is being imported into App.js, I'd like to pass those two components into the <CallOut /> component.
What is the correct syntax to pass those two in and have them placed in the same spot they're currently in within the CallOut component?
I believe it should be something similar to
<CallOut param={List} param={BoxRight} />
but I know this isn't right.
You can use capital names for props, and use these to instantiate react components like this:
export const CallOut = ({List, Box}) => (
<div style={styles.sectionInner}>
<List/>
<Box/>
</div>
);
List and Box are the properties of this component. You can instantiate it like this:
<CallOut List={SomeComponent} Box={SomeOtherComponent}/>
I don't know if we're on the same page but maybe you're looking for children property ?
So your component will look like that:
export const CallOut = ({children}) => (
<div style={styles.sectionInner}>
{children}
</div>
);
And usage:
<CallOut >
<List/>
<Box/>
</CallOut>
You can pass any component as CallOut child or even do some filtering using children API
It's common usage when components don’t know their children ahead of time and it's used just for some kind of boxing/wrapping.

React js: component is not unmounted properly

We have following scenario:
1. Parent component has child components.
==============================================================
<ContainerComponent>
<Layout>
<CustomComponent>
<ActualComponent>
<CustomComponent>
<ActualComponent>
==============================================================
This way component mounting takes place, and each ContainerComponent rendered according to task.
Component Container contain :
return (
<div className='row' >
<div className='col-md-12' >
<div className="ic-component" id="MainComponent" >
<div style={{'border':'5px;solid #e0e7f0'}}>
<div id="rootwizard3" className='wizard'>
<ul>
{TabHeader}
</ul>
<div className="tab-content" id="tabcontent" >
</div>
</div>
</div>
</div>
</div>
</div>
);
Then ContainerComponent contain Layout component :
$("#tabcontent").empty();
if(LayOut===null)
{
}
else {
React.render(
<div id={tabid}><div id={layoutid}>
<LayOut CurrentStepId={CurrentStepId} TaskDetails={TaskDetails} IsActualComponent="true"/>
</div>
</div>,document.getElementById('tabcontent'));
}
},
Layout component contains CustomComponent :
var findDiv1=$("div > #"+TabbId+" > div > div > div > div > div")[0];
$(findDiv1).empty();
var valueP3=1;
React.render(<CustomComponent inputType={Set} ItemName="" ItemId="" KeyValue={valueP3} addbtndispaly="" editbtndispaly="" deletebtndispaly="" Views="" />,findDiv1);
Unmounting of Container page:
React.unmountComponentAtNode(document.getElementById('tabcontent'));
Following way the components get mounted.
Initial component mounting. Here layout component loaded into Container Component. but custom component is not showing under Layout ? but output is poperly showing.
chrome react tool component loading structure
Second time component mounting, but here it only remove component under "ctab137". not unmounting custom component . Second copy of cutom component get created.
chrome react tool component loading structure-Second time loading
When we go to task(functionality) it mounts parent component and accordingly
respective child component gets mounted.
When we click to another task mean containerComponent then only containerComponent unmount get called. for that we are clearing container componenet div where its child componenet get mounted. and load another task child componenet.
But here is we are facing problem when we mount child componenet every times it get mounted separately if that component is already present. and that create problem. Here is above mentioned custom component is not get propely unmounted. Every time separate customComponent copy is created and that times that funtionality get executed.
Also here is child componenets componentWillUnmount not get called.
I want to know answers of following questions .
How to unmount child components if it is not unmounted ?
How to call child components unmount method if it's not called ?
Is there any way to unmount component by component name ?

Resources