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

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>
);
};

Related

Icons are not showing in navbar

Hi so this is my navbar that i created with some icons that navigate between screens when i press them , the icons looks fine on my project with expo (without Android and ios folders)
this is my code:
import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createMaterialBottomTabNavigator } from '#react-navigation/material-bottom-tabs';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import EmptyHistory from '../Accueil/EmptyHistory.js'
import Profile from '../Accueil/Profile.js'
import Accueil from '../Accueil/Accueil.js';
const Tab = createMaterialBottomTabNavigator();
function MyTabs() {
return (
<Tab.Navigator
barStyle={{ backgroundColor: '#FFFFFF' }}
initialRouteName="Accueil"
activeColor="#D05A0B"
>
<Tab.Screen
name="Historique"
component={EmptyHistory}
options={{
tabBarLabel: 'Historique',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="history" color={color} size={26} />
),
}}
/>
<Tab.Screen
name="Accueil"
component={Accueil}
options={{
tabBarLabel: 'Accueil',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="food" color={color} size={26} />
),
}}
/>
<Tab.Screen
name="Profile"
component={Profile}
options={{
tabBarLabel: 'Profile',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="account" color={color} size={26} />
),
}}
/>
</Tab.Navigator>
);
}
export default function Navbar() {
return (
<NavigationContainer>
<MyTabs/>
</NavigationContainer>
);
}
So i switched my project using npx react-native (with Android and ios folders) and i did all the installs including the vector icons
but the results are not the same , my icons are not showing properly in my navbar
is there any solution for this ?
To install icons in bare react native is as same as putting new fonts in react native, so you can follow this https://mehrankhandev.medium.com/ultimate-guide-to-use-custom-fonts-in-react-native-77fcdf859cf4

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 !

Styling is not applied to styled component using style(StyledComponent) syntax

Styling a div using style.div works just fine.
But styling a styled component using style(FlexItem) does nothing.
What might be the reason?
import * as React from 'react';
import OuterSectionContainer from './../../ui/OuterSectionContainer';
import InnerSectionContainer from './../../ui/OuterSectionContainer/InnerSectionContainer';
import FlexContainer from './../../ui/OuterSectionContainer/InnerSectionContainer/FlexContainer';
import FlexItem from './../../ui/OuterSectionContainer/InnerSectionContainer/FlexContainer/FlexItem';
import ScaledImage from './../../ui/ScaledImage';
import styled from 'styled-components';
const Testamonials = () => {
const FlexItemStyled = styled(FlexItem)`
padding: 10px;
background-color: red;
display: none;
`;
return (
<OuterSectionContainer>
<InnerSectionContainer>
<FlexContainer>
<FlexItemStyled>
<ScaledImage src={require('../../../images/logo.png')} />
</FlexItemStyled>
<FlexItemStyled>
<ScaledImage src={require('../../../images/logo.png')} />
</FlexItemStyled>
<FlexItemStyled>
<ScaledImage src={require('../../../images/logo.png')} />
</FlexItemStyled>
<FlexItemStyled>
<ScaledImage src={require('../../../images/logo.png')} />
</FlexItemStyled>
</FlexContainer>
</InnerSectionContainer>
</OuterSectionContainer>
);
};
export default Testamonials;
FlexItem should not be a styled-components, then you should pass className in props to use styled(FlexItem) syntax.
more info here : https://www.styled-components.com/docs/basics#styling-any-components

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} />

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