In React application, Images cannot show when an image url is string property of a object - html

I cannot show the image when the image url is string property in a object.
For example:
import React, {Fragment, useState} from 'react';
const profile = (props) => {
const [user, setUser] = useState(null);
useEffect(() => {
setUser({
name: 'John',
photo: './asset/images/user.png'
})
}, [])
return (
<Fragment>
<img src={user.photo} alt="photo" />
<p>{user.name}</p>
</Fragment>
)
}
Of course I can solve this by importing image object like import img from './assets/images/user.png'. But I need to know how to show image without importing it.
Does anyone solve the problem?

You can see one example working here: https://codesandbox.io/s/relaxed-sinoussi-ikown?file=/src/App.js
The main problem is you're trying to access the image as a relative route from your component.
But, when you want to do something like that your component can be anywhere in the application. So, the way to do it is:
Include your images in public/
Access your images using the absolute route from /public

Related

Custom Styled Input field in react js

I am looking for input field which take the input in formated way based on user selection of font, bullets and code type.
Provided the image below
Code should be in React Js and output can be html in json format
You're trying to say you need to implement a rich text editor using React?
Well, in that case I personally use jodit-react because it's open-source, works well with TypeScript and NextJS and outputs the text in HTML format. You can find the project here and basic implementation looks like this.
import React, {useState, useRef, useMemo} from 'react';
import JoditEditor from "jodit-react";
const Example = ({placeholder}) => {
const editor = useRef(null)
const [content, setContent] = useState('')
const config = useMemo({
readonly: false // all options from https://xdsoft.net/jodit/doc/,
placeholder: placeholder || 'Start typing...'
},
[placeholder])
return (
<JoditEditor
ref={editor}
value={content}
config={config}
tabIndex={1} // tabIndex of textarea
onBlur={newContent => setContent(newContent)} // preferred to use only this option to update the content for performance reasons
onChange={newContent => {}}
/>
);
}
Take a look at this example below.
Hope this helps!
Cheers!

I am displaying dynamic data on this React Boostrap Slider. Is there a way to make the code more efficient?

this is my first post here. I am building a React Boostrap Carousel that pulls Movie data from the database and displays it. I am new to React and programming in general. So far i made the code work. But i do not know how to handle the images. The images are stores in React **src/assets/imgs. **. Should i store a reference to the image in the database like so ../../assets/imgs/the-batman.jpg and then display it? If so later on on the project the admin will have to create a MovieOfTheMonth. He should be able to input movie title, descrition etc, and also upload a movie image. Is there a way when the image is uploaded it, to store it to a specific folder, in this case src/assets/imgs and also create a reference in the database? I do not need the solution here, just to tell me if it is achievable. Finally is there a way to improve my code?
this is my full code for this component
import React, {useState, useEffect } from 'react';
import './Carousel.css'
import Carousel from 'react-bootstrap/Carousel';
import 'bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios';
const CarouselHero = () => {
//boostrap code
const [index, setIndex] = useState(0);
const handleSelect = (selectedIndex, e) => {
setIndex(selectedIndex);
};
//Get Movies of the month
const [movie, setMovie] = useState([])
const getMovie = () => {
axios.get("http://localhost:4000/moviesOfTheMonth")
.then((res) => {
const myMovie = res.data
myMovie.push()
setMovie(myMovie);
})
}
useEffect(() => getMovie(), []);
return (
<Carousel activeIndex={index} onSelect={handleSelect} fade>
{movie.map((item) => {
const {id, title, description} = item.Movie
return (
<Carousel.Item interval={2000}>
<img
src={require("../../assets/imgs/the-batman.jpg")}
alt="First slide"
/>
<Carousel.Caption >
<h1>{title}</h1>
<p>{description}</p>
<button>Book Now</button>
</Carousel.Caption>
</Carousel.Item>
)
})}
</Carousel>
);
};
export default CarouselHero;
I think technically it is achievable to iterate over the assets folder and create database entries for new images (create and compare hash?), but it is usually not how you do it. I would put images in some file storage like S3 and reference them with id.
I don't know who the admin will be in your project, but if admin is rather a non technical person, you could create (or use a template of course) a small and simple admin dashboard, where he/she can maintain a movie of the month via UI.
FFinally some remarks on your code:
const handleSelect = (selectedIndex, e) => { setIndex(selectedIndex); }; - If you need only first, but not second, third etc. argument, you can just leave it out: (selectedIndex) => ...
const [movie, setMovie] = useState([]) - don't forget to use semicolon after every statement. (They are optional, but are useful sometimes to avoid weird errors). Also, you have a list here. So maybe better call it "movies".
myMovie.push() - What are you trying to push here?
useEffect(() => getMovie(), []); - Usually you define and call async function directly in useEffect. Don't you get any hints or warning?
movie.map((item) => { - When you iterate and get a list back React needs a key on every element (here on Carousel.Item). Don't just use the index, as it is a bad practice. Always try to find id property in your data.
const {id, title, description} = item.Movie - Why is the data nested by Movie object? Can't you just say item.id, item.title, item.description?

How to render an element in React which was created by createElement()?

I have created an image element by using:
const image = document.createElement('image'); // or new Image();
How can I render this image variable in React ?
I don't want to use Html tags to do something like this:
<img src={image.src} ... />
Is there any other way ?
Well either create a <div class="parent"> </div> and then use
document.querySelector(".parent").appendChild(imageElement)
or simply,
document.appendChild(imageElement)
This is the wrong way to go about doing this. You shouldn't directly manipulate the DOM with React. I would instead have an array of objects in your state, and in your component, map the objects to the elements of your choosing. Like this
const Component = () => {
const [components, setComponents] = useState([{src:'path/to/src', alt:'altTag'}])
return(
<>
{
components.map(e => {
return(<img src={require(e.src)} alt={e.alt} />)
})
}
</>
)
}
Wrote this from memory/without testing so there might be something wrong so dont kill me. But if you need to render it anywhere, make it its own component. If it's truly just one image, then you don't need the array/map just use an object and render it same way

How to navigate in React-Native?

I am using ReactNavigation library in my react-native project and since 6 hours I am trying to navigate from one screen to others screen and have tried every possible way but I think I am not able to get the logic properly.
This is my project structure.
Here
The way I am doing it.
const AppStack = StackNavigator({ Main: Feeds });
const AuthStack = StackNavigator({ Launch: LaunchScreen, });
export default SwitchNavigator({
Auth: AuthStack,
App: AppStack
});
In my LaunchScreen.js
const SimpleTabs = TabNavigator(
{
Login: {
screen: Login,
path: ""
},
SignUp: {
screen: SignUp,
path: "doctor"
}
},
);
<SimpleTabs screenProps={{rootNavigation : this.props.navigation }}/>
But the problem is in my LaunchScreen Component there is a TabNavigator which contains my other two components Login.js and SignUp.js but the button in my Login.js doesn't navigate it to Feed.js.
When you click on the button this is performed.
signInAsync = async () => {
await AsyncStorage.setItem('userToken', 'abc');
this.props.navigation.navigate('Main');
console.log("AAAAAsSSS");
};
My LaunchScreen.js contains a TabNavigation which lets you slide between two components ie. Login.js and SignUp.js.
Now when you click on the Login button which is in Login.js component it will authenticate the user and will switch the entire LauchScreen.js component with the Feed.js component.
I am a noob to react-native.
You can use react-native-router-flux (npm install --save react-native-router-flux)
just make one Navigator.js file and define each page you wanted to navigate.
import React from 'react';
import { Router, Scene } from 'react-native-router-flux';
import LaunchScreen from '../components/LaunchScreen.js';
import Feed from '../components/Feed.js';
const Navigator = () => {
return (
<Router>
<Scene key="root">
<Scene key="lauchscreen" component={LaunchScreen} hideNavBar initial />
<Scene key="feedscreen" type="reset" hideNavBar component={Feed} />
</Scene>
</Router>
);
};
export default Navigator;
now in your App.js file add this:
import Navigator from './src/Navigator.js';
export default class App extends Component<Props> {
render() {
return (
<Navigator />
);
}
}
now in your login.js when you click on login button write this:
import { Actions } from 'react-native-router-flux';
onLoginClick() {
Actions.feedscreen();
}
Thats it.. happy coding.
If you want to navigate to Feeds.js then navigate as
this.props.navigation.navigate('App');
not as
this.props.navigation.navigate('Main');
because your
export default SwitchNavigator({
Auth: AuthStack,
App: AppStack // here is your stack of Main
});
refer example
I came across the same issue few months ago. Thank god you have spent just 6 hours, i almost spent around 4 days in finding a solution for it.
Coming to the issue, Please note that in react-navigation you can either navigate to siblings or children classes.
So here, You have a swtichNavigator which contain 2 stack navigators (say stack 1 and stack 2), stack1 has feeds and stack2 has a tab navigator with login and signup.
Now you want to navigate from login.js to feeds.js(say file name is feeds.js). As mentioned already you can not navigate back to parent or grandparent. Then how to solve this issue?
In react native you have the privilege to pass params (screenprops) from parent to children. Using this, you need to store this.props.navigation of launchScreen into a variable and pass it to tab/login (check the tree structure). Now in the login.js use this variable to navigate.
You are simply passing the navigating privilege from parent to children.
Editing here:
<InnerTab screenProps={{rootNavigation : this.props.navigation }} />
Here, InnerTab is the tab navigator.
export const InnerTab = TabNavigator({
login: {
screen: login,
},
},
signup: {
screen: signup,
},
},
},
in login class, use const { navigate } = this.props.screenProps.rootNavigation;
Now you can use variable navigate.
I know its little tricky to understand but i have tried and it works.
Write your Navigator.js file as below,
import React from 'react'
import { NavigationContainer, useNavigation } from '#react-navigation/native'
import { createStackNavigator } from '#react-navigation/stack'
const SwitchNavigatorStack = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='{nameofscreen}' screenOptions={screenOptions}>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default SwitchNavigatorStack
Once, you are done with that change your App.js file to,
import SignedInStack from './navigation'
import React from 'react'
export default function App() {
return <SwitchNavigatorStack/>
}
After this, you are done with setting your project for navigating. In all the components where you want to add navigation feature make sure you use the navigation.navigate() (or) navigation.push() method. Also make sure you hook navigation constant by import useNavigation library. For example,
const Login = () => {
const navigation = useNavigation()
< Button title = 'Login' onPress={() => navigation.navigate('{nameofscreen}')} />
}
with this code snippet you can implement navigation between screens using #react-navigation/native and #react-navigation/stack

Render React Native Elements from JSON

I have searched around...can't quite find what I'm looking for, so I appreciate any help! Here is what I am going for:
I am building a CMS-like setup for a React Native app. This is so that an admin of an app can login to the CMS dashboard, and update a page/view of the app without having to go into the hardcode. I would like them to be able to choose from a pre-set list of components and be able to drag-and-drop them into the app, in whatever order they would want and be able to update the content and colors, etc. Let me provide an example...
There is a home page that I imagine having a rotating banner at the top, then a button for a information modal, then a set of menu links to go to sub-child pages.
So what I think, development-wise, is to give the app admin a WYSIWYG type of setup, and to store the result of this in the Database. It could store in the database as:
<RotatingBanner />
<Modal />
<ContentMenu>
<ContentMenuLink title="About" />
<ContentMenuLink title="Competitive" />
<ContentMenuLink title="Recreational" />
<ContentMenuLink title="Tournaments" />
<ContentMenu />
Right now, when I try to render this into a screen, I continue to have it render that as the actual words vs the components they are representing if that makes sense. So the page looks just like the code block above, instead of seeing a rotating banner and modal, etc.
I have tried a tool to convert HTML into React Native elements...does anyone know how I can convert a fetched JSON that would look like:
{content: "<RotatingBanner /><Modal /><ContentMenu>...."}
and have it create the real components in the render function? Any other thoughts or ideas/advice on creating a CMS like this are greatly appreciated if you would like.
Thanks!
Let's say your have this JSON:
const data = {
"components": [
{"name": "component1", props: {"hello": "world"}},
{"name": "component2", props: {"color": "red"}},
]
}
Make your components and then reference them in an Object (map):
import Component1 from './Component1'
import Component2 from './Component2'
const COMPONENT_MAP = {
component1: Component1,
component2: Component2,
}
Then make your wrapper component:
const Wrapper = ({data}) => (
<View>
{data.components.map(({name, props}) => {
const Component = COMPONENT_MAP[name]
return <Component {...props} />
}}
</View>
)
VoilĂ  :)
<Wrapper data={data} />
I would recommend using Array's to save and render multiple childrens
const Component1 = () => <Text>One</Text>
const Component2 = () => <Text>One</Text>
const childs = [
Component1,
Component2
]
return childs
React is able to render arrays as they are.
Other possible solution could be,
return Object.keys(child).map(item => childs[item] )
A quick solution can be react-native-dynamic-render
Also, you can render nested components with that.
A complete example is here