React Responsive Media Queries Not Changing - node.js

I'm using react responsive to create media queries so an image size will change. However, it's not doing what I want. It keeps the larger 1st image on the screen and doesn't switch over to the other with the rules I specified. Is there a different way of coding this?
import React, {Component} from 'react';
import MediaQuery from 'react-responsive'
class Name extends Component {
render(){
return(
<>
<div>
<MediaQuery Nameimg={this.props.Nameimg} minWidth={900}>
<img height="15vh" className="name_image" src={this.props.Nameimg} alt="name"/>
</MediaQuery>
<MediaQuery Nameimg={this.props.Nameimg} maxWidth={899}>
<img height="8vh" className="name_image2" src={this.props.Nameimg} alt="name2"/>
</MediaQuery>
</div>
</>
)
}
}
export default Name;

This was a simple fix so hopefully this is useful to someone else as well. But I believe it wasn't working because you need to use set widths defined by the package https://github.com/contra/react-responsive/blob/master/src/mediaQuery.ts#L9
I used minWidth and maxWidth of 1224, which did the trick.

Related

Load specific DIV with a react component without reloading the whole page

I have a menu where every menu item is a button and I want to load a specific reactjs component into a specific div without reloading the whole page.
This is the current code, clearly is bad but I don't know where to start fixing it...
...
<Button onClick={this.loadTarget}>
{menuItem.name}
</Button>
...
loadTarget(event) {
document.getElementById("datapanel").innerHTML="abc<TranslationsList />";
}
When I click a menu Item I want to load my div with the value "abc<TranslationsList />". "abc" is displayed but the custom component "TranslationsList" is not and I guess this is normal as the TranslationsList tag is not a HTML tag. But how could I load my component?
I could use links instead of buttons but in this case the question is how could I update the div content with a specific link?
It's hard if you've programmed plain JS before, but you have to forget the "good old JS pattern" in React. I also had a hard time getting used to not using standard JS elements (target, innerHTML, etc.) to solve such a problem.
So the solution in React is to use the framework and your page reload problem will be solved immediately. useState for the state of the component and handlers for the click. My main code looks like this. You can find a working application at Codesandbox.
export default function App() {
const [showComponent, setShowComponent] = useState(false);
const handleButtonClick = (e) => {
setShowComponent(!showComponent);
};
return (
<div className="App">
<h1>
Load specific DIV with a react component without reloading the whole
page
</h1>
<a href="https://stackoverflow.com/questions/74654088/load-specific-div-with-a-react-component-without-reloading-the-whole-page">
Link to Stackoverflow
</a>
<div style={{ marginTop: "20px" }}>
<button onClick={handleButtonClick}>Magic</button>
</div>
{showComponent ? (
<div style={{ marginTop: "20px" }}>
This is the place of your component!
</div>
) : (
""
)}
</div>
);
}
In the first place I wpuld not use vanilla JS syntax on a react app if it is not necessary. i.e: document.getElementById("datapanel").innerHTML="abc<TranslationsList />".
If you are using React you should be managing the State in the component of the DIV, giving the order to make an element appear once the button is clicked.
A simple example can be this:
CodeSandbox
import { useState } from "react";
export default function App() {
const [divState, setDivState] = useState(null);
const divElement = () => <div>I am the element that should appear</div>;
const handleDiv = () => {
setDivState(divElement);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={handleDiv}>Show DIV</button>
<div>{divState}</div>
</div>
);
}
I agree with the answers given above. Since you are already using React, you should take advantage of its features/functionalities. No need to reinvent the wheel.
However, if you are still interested in how to make your current implementation work. You may use renderToString(), which can be imported from ReactDOMServer. Please refer to the following code snippet as an example.
import { renderToString } from 'react-dom/server'
const TranslationsList = () => {
return <div>TranslationsList Content</div>
}
export default function App() {
const loadTarget = () => {
document.getElementById("datapanel").innerHTML=`abc${renderToString(<TranslationsList />)}`;
}
return (
<div>
<button onClick={loadTarget}>Insert Component</button>
<div id="datapanel">Data Panel Holder</div>
</div>
);
}

how to pass a link to another components in react

I am trying to pass a Link it has a films id to another component named movie detail js.
the problem I am having is connecting Movies Container link to movie detail. Please help
MoviesContainer.js
<Link to={ `/movie/${films.id}${config.apiKey}` }>
<button className='successW' > GET INFO </button>
</Link>
MovieDetail.js
import React, { Component } from 'react';
import axios from 'axios';
import './MovieDetail.css';
import { props , match , params, } from 'react-router-dom';
//import config from '../../config.js';
import films from '../MoviesContainer/MoviesContainer.js';
import router from '../../router.js'
export default class MovieDetail extends Component{
constructor(props){
super(props);
this.state= {
movie:[]
}
}
componentWillMount(){
axios.get(`/movies/:id`).then(response=> {
console.log(response.data.results);
this.setState({ moviesList: response.data.movie });
});
}
render(){
console.log( this.setState.movie);
const imgURL= 'http://image.tmdb.org/t/p/original';
return(
<div className='moviecd'>
<img style={{ height: '85%', width: '100%' }} src={ imgURL + this.state.movie.poster_path } alt='movie poster'></img>
</div>
)
}
}
ı guess you are using React-Router. First of all, you can specify the path you will use in the Router system and which component should be installed if this path is used. For Example :
<Route exact path="/movies/:movieId" component={MovieDetails} />
This is the system you should use for your router.
and there is a button to go to the MovieDetails.js component.
you should wrap this button with a Link(React-Router). Like This:
<Link to = {{pathname: `${movieId}`}}> // The id of the movie you clicked
<button>Go Movie </button>
</Link>
Now, if you clicked on which movie you clicked on, the id of that movie will go to the MovieDetails.js component as a props.
If you browse the props coming to the MovieDetails component, you will find a props like params.match.movieId.
You can now use this id when making a request (Inside the MovieDetails component). Like This:
fetch(`https://api.themoviedb.org/3/movie/${this.props.match.params.movieId}?api_key=<yourapikey>`)
How you process it after you get the data is up to you!
I hope it was understandable. Good Luck !

Vuetify, how to style/theme a button to always be "small" and "tile"?

How can I change the default appearance of a button, so every time I create a button it will look the same? I understand how to i.e. use the color theme to change the i.e. "primary" color, and how to change the css for i.e. all button background colors.
But how would I go about if I for example want:
All buttons to automatically appear as "small" and "tile" by default?
Create your own component, e.g. like this one at src/components/XBtn.vue:
<template>
<v-btn
v-bind="$props"
small
tile
v-on="$listeners"
>
<slot></slot>
</v-btn>
</template>
<script>
import VBtn from 'vuetify/lib/components/VBtn/'
export default {
name: 'XBtn',
props: VBtn.options.props,
}
</script>
Then elsewhere in your app, you can import it:
<template>
<v-row>
<x-btn color="primary">Save</x-btn>
</v-row>
</template>
<script>
import XBtn from '#/components/XBtn'
export default {
name: 'SomeOtherComponent',
components: {
XBtn,
},
}
</script>
Or if you want it to be globally available without having to import it each time, you can register it in src/main.js like this:
// ... other imports ...
import XBtn from '#/components/XBtn'
Vue.component('x-btn', XBtn)
new Vue({
// ... main Vue instance config ...
})
The cool thing about doing it this way is that the XBtn component you derive from VBtn will have ALL of the same properties and events. XBtn will default to small and tile but you can still override these by doing something like: <x-btn large>. You basically use it the exact same way that you use VBtn.

Importing an image into an <src> tag in React.js when the image name is not known in advance

I have a component in React which displays (or doesn't at the moment) an image within an src tag.
The file path & file name of the image is passed via props after being selected by the user, so I can't do an import at the top of the file. Apparently, I should be able to do something like src={require(file)} but this causes webpack to throw a hissy fit and give the following error: Error: cannot find module "."
As an e.g., a typical filepath/filename I pass to the component is: '../../../images/black.jpg'
This is a stripped-down version of the code in question:
import React, { Component } from "react";
class DisplayMedia extends Component {
render() {
return (
<div className="imgPreview">
<img src={this.props.file} alt="piccy" />
</div>
);
}
}
export default DisplayMedia;
Depending on your set up...
If the images are dynamic (during production, images will be added, edited, or deleted):
I'd recommend a microservice that only handles images. I go in depth on how to approach such a service: Image returned from REST API always displays broken
If the images are static (during production, the images are bundled within the "bundle.js" file):
- I'd recommend importing all of the images within the component, creating an array of the imported images, and then utilizing the array index and React state to cycle through them. For example:
import React, { Component } from "react";
import Image1 from "../images/Image1.png";
import Image2 from "../images/Image2.png";
import Image3 from "../images/Image3.png";
const images = [Image1, Image2, Image3];
export default class ShowImage extends Component {
state = { index: 0 };
handleChange = ({ target: { value } }) => {
this.setState({ index: value });
};
render = () => (
<div className="container">
<h1>Utilizing Array Indexes</h1>
<select
style={{ marginBottom: 20 }}
value={this.state.index}
onChange={this.handleChange}
>
{images.map((val,idx) => (
<option key={idx} value={idx}>Image {idx + 1}</option>
))}
</select>
<img src={images[this.state.index]} />
</div>
);
}
While I can't create an exact codesandbox of the above, this working example should give you the basic idea: https://codesandbox.io/s/ovoo077685
You don't need to add require in src. When relative path is used it will go the images availale in your server but when url is given image will be loaded. You can find more info here
When using src as /images/black.jpg it will convert to localhost:3000/images/black.jpg

svg into react-native project

Since the last 72 hours, I have lost my mind trying to figure this out.
All I want to do is use my vectors from illustrator and display them on my react-native app.
I tried a few libraries like react-native-vector-icons used icomoon followed steps, no result.
Please guide me a perfect solution to this issue. I have no web developer experience, all I know is Javascript and react-native and illustrator.
// Code
import React, {Component} from "react";
import {View, Text} from "react-native";
import {Font} from "expo";
import {createIconSetFromIcoMoon} from "react-native-vector-icons";
import icoMoonConfig from "../selection.json";
const Icon = createIconSetFromIcoMoon(icoMoonConfig);
Expo.Font.loadAsync("icomoon", require("../assets/fonts/icomoon.ttf"));
export default class INITIATE extends React.Component {
async componentDidMount() {
await Font.loadAsync("icomoon",
require("../assets/fonts/icomoon.ttf"));
this.setState({fontLoaded: true});
}
state = {
fontLoaded: true
};
render() {
return (
<View style={{
flex: 1, justifyContent: "center", alignItems:
"center"
}}>
{this.state.fontLoaded ? <Icon/> : null}
</View>
);
}
}
// The screen renders blank
React Native is for Android and iOS apps and React JS is for web development.
In React, import the SVG image first:
import sampleSvg from 'imgPath/sample.svg';
Then load it with:
<img src={sampleSvg} alt="A Sample SVG Image" />
For React Native, there's a similar question with an answer using webView.
Or try react-native-svg-uri
Hope it can help!
Using SVG icons with React is pretty simple.
Create an Icon component.
import IcoMoon from "react-icomoon";
import { Svg, Path } from "react-native-svg";
const iconSet = require("./selection.json");
const Icon = (props) => (
<IcoMoon
native
SvgComponent={Svg}
PathComponent={Path}
iconSet={iconSet}
{...props}
/>
);
export default Icon;
Import and use anywhere.
import Icon from "./icon";
<Icon icon="pencil" size={20} color="orange" />;
For more information: react-icomoon

Resources