svg into react-native project - svg

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

Related

React Responsive Media Queries Not Changing

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.

With styled components how to pass theme color from Global Style to React Icons Context Provider?

Looking for a way to pass color from theme to React Icons. Theme is working correctly and I'm able to pass colors to my styled components. Here is the breakdown:
index.js:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
// Theme
import { ThemeProvider } from 'styled-components'
import { GlobalStyles } from './theme/GlobalStyles'
import Theme from './theme/theme'
ReactDOM.render(
<ThemeProvider theme={Theme}>
<GlobalStyles />
<App />
</ThemeProvider>,
document.getElementById('root'),
)
app.js (stripped down):
<IconContext.Provider value={{ color: `${({ theme }) => theme.colors.white}` }}>
<FaTimes />
<FaBars />
</IconContext.Provider>
the equivalent of:
<IconContext.Provider value={{ color: `#fff` }}>
<FaTimes />
<FaBars />
</IconContext.Provider>
does work and I did try:
NavElements.js:
import { IconContext } from 'react-icons/lib'
export const NavProvider = styled(<IconContext.Provider>{children}</IconContext.Provider>)`
color: ${({ theme }) => theme.colors.color2};
`
app.js:
// <IconContext.Provider value={{ color: `#fff` }}>
<NavProvider>
// Further code
</NavProvider>
// </IconContext.Provider>
but I get a children error. Attempt came from reading Q&A Styled-components and react-icons <IconContext.Provider> component
Other Q&As I found with no luck:
How to Style React-Icons
react-icons apply a linear gradient
With a theme color in Styled Components how can I pass that color to React Icons Provider?
I haven't worked with react-icon but this might help
Take a look at getting the theme without styled components - there is also a hook
Your example
export const NavProvider = styled(<IconContext.Provider>{children}</IconContext.Provider>)`
color: ${({ theme }) => theme.colors.color2};
`
work because styled expects a HTML element or a React component
Your NavProvider could be something like (haven't tried this code but it should work)
import { useContext } from 'react';
import { ThemeContext } from 'styled-components';
export const NavProvider = ({children}) => {
const themeContext = useContext(ThemeContext);
return (
<IconContext.Provider value={{ color: themeContext.colors.color2 }}>
{children}
</IconContext.Provider>
);
};

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 !

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

Styling react-select with styled-components

I'm trying to change the color of the select-up-arrow and the color of the control when it's in focus, but without success. Have anyone done this using styled-components?
This applies to react-select#v2.*
The same ideas as #bamse answer can be applied to v2 of react-select. The problem is that in v2 they removed pre-determined class names unless you specify to add them in with the prop classNamePrefix. They also changed what the class names in general look like.
General solution is to make sure to add in the class names with the prop classNamePrefix, then use styled around ReactSelect and target classes within it.
import React from 'react';
import ReactSelect from 'react-select';
import styled from 'styled-components';
const ReactSelectElement = styled(ReactSelect)`
.react-select__indicator react-select__dropdown-indicator {
border-color: transparent transparent red;
}
`;
export (props) => <ReactSelectElement classNamePrefix="react-select" {...props} />
This applies to react-select#v3.*
I had the same problem and solved it like this:
CustomSelect.js file:
import ReactSelect from 'react-select';
import styled from 'styled-components';
export const CustomSelect = styled(ReactSelect)`
& .Select__indicator Select__dropdown-indicator {
border-color: transparent transparent red;
}
`;
TheComponent.js file:
import React from 'react';
import { CustomSelect } from './CustomSelect';
export function TheComponent () {
return <div>
<CustomSelect
classNamePrefix={'Select'}
{* props... *}
/>
Something awesome here...
</div>
}
`;
Note the classNamePrefix={'Select'} in TheComponent.js - that's important.
This applies to react-select#v1.*
Here you can find an example of styling react-select with styled-components.
To change to caret's colour when the select is opened you can use this
&.Select.is-open > .Select-control .Select-arrow {
border-color: transparent transparent red;
}
The component would look like
import React from 'react';
import ReactSelect from 'react-select';
import styled from 'styled-components';
const RedCaretWhenOpened = styled(ReactSelect)`
&.Select.is-open > .Select-control .Select-arrow {
border-color: transparent transparent red;
}
`;
export (props) => <RedCaretWhenOpened {...props} />

Resources