logo
down
shadow

How to serve a React component library dependent on Styled Components to another library that also has a Styled Comopnen


How to serve a React component library dependent on Styled Components to another library that also has a Styled Comopnen

By : Gael
Date : November 21 2020, 07:01 PM
seems to work fine This is only a partial answer that I'm hoping will enable you or someone else to figure out the rest. I'm far from an expert on managing these kind of dependencies and am helping with this to further my own knowledge since I may want to do a similar setup soon.
Though it seems this should be doable with nwb, I switched to using webpack directly in order to have more control. Even using webpack directly I have only made it part of the way there. Everything works correctly when I do a build, but in dev mode (npm start) for the CRA app, the styled-components package is still getting pulled in twice and the styling doesn't work correctly. This seems like a potential webpack issue since the dev and production modes behave so differently, but it could be something with the CRA webpack dev configuration or (more likely) some aspect of this that I don't yet understand.
code :
{
  "name": "component-lib3",
  "version": "1.0.7",
  "description": "component-lib3 React component",
  "main": "dist/component-lib3.js",
  "peerDependencies": {
    "react": "^16.6.0",
    "react-dom": "^16.6.0",
    "styled-components": "^4.0.3"
  },
  "devDependencies": {
    "react": "^16.6.0",
    "react-dom": "^16.6.0",
    "styled-components": "^4.0.3",
    "@babel/core": "^7.1.2",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.4",
    "webpack": "^4.24.0",
    "webpack-cli": "^3.1.2"
  },
  "scripts": {
    "build": "webpack"
  }
}
var path = require('path');

module.exports = {
  entry: './src/index.js',
  mode: 'production',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'component-lib3.js',
    libraryTarget: 'umd',
    library: 'component-lib3'
  },
  externals: {
     "styled-components": {
       commonjs: 'styled-components',
       commonjs2: 'styled-components',
       amd: 'styled-components'
     },
     "react": {
       commonjs: 'react',
       commonjs2: 'react',
       amd: 'react'
     },
     "react-dom": {
       commonjs: 'react-dom',
       commonjs2: 'react-dom',
       amd: 'react-dom'
     }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};
{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}


Share : facebook icon twitter icon
Dynamically Styled Button in React Native using Styled Components

Dynamically Styled Button in React Native using Styled Components


By : codorkh
Date : March 29 2020, 07:55 AM
wish helps you A Button component is generally comprised of the Text element wrapped with a TouchableHighlight (or other touchable). I'm trying to create a Button component styled using styled-components, but am having trouble getting my style to respond dynamically to props. , Here you have:
code :
const Button = (props) => {
    return (
        <ButtonContainer underlayColor={colors.highlight}>
            <Label>
                {props.children}
            </Label>
        </ButtonContainer>
    );
};
const Button = (props) => {
    return React.createElement(ButtonContainer, { underlayColor: colors.highlight }, ...);
};
const Button = (props) => {
    return (
        <ButtonContainer underlayColor={colors.highlight} onPress={props.onPress} outline={props.outline}>
            <Label outline={props.outline}>
                {props.children}
            </Label>
        </ButtonContainer>
    );
};
With a Styled-Components, how to set an array of colors outside of the Styled Component?

With a Styled-Components, how to set an array of colors outside of the Styled Component?


By : Kiranjith Tg
Date : March 29 2020, 07:55 AM
should help you out So I have done this in react-native and should be pretty similiar. I have a file called colors.js with all of the colors then I import them as an object so that was I can say colors[TheNameOfTheColorIWant]
colors.js
code :
export const fadedPurple = '#9f91ad';
export const success = '#4fa579';
export const failure = '#ca374d';
import * as colors from '../../../assets/styles/colors';

const Button = (props) => {
  const {
    onPress,
    children,
    color
  } = props;

  style = {
    backgroundColor: colors[backgroundColor]
  }

  return (
    <TouchableOpacity style={ style }
                      onPress={ onPress }
                      disabled={ disabled }>
        { children }
    </TouchableOpacity>
  )
styled-components is saying wrapped styled() around your React component (Component)

styled-components is saying wrapped styled() around your React component (Component)


By : user2076262
Date : March 29 2020, 07:55 AM
like below fixes the issue Basically, you need to pass this.props.className or props.className or a deconstructed className that was generated by styled-components and manually apply it to the component you want to style. Otherwise, you're not applying the className to anything and therefore won't see any style changes.
Working example:
code :
import React from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";

const LinkComponent = ({ className, children, link }) => (
  <Link className={className} to={link}>
    {children}
  </Link>
);

LinkComponent.propTypes = {
  className: PropTypes.string.isRequired,
  link: PropTypes.string.isRequired,
  children: PropTypes.string.isRequired
};

export default LinkComponent;
import styled from "styled-components";
import LinkComponent from "./LinkComponent";

const StyledLink = styled(LinkComponent)`
  color: ${props => (!props.primary && !props.danger ? "#03a9f3" : "#ffffff")};
  background-color: ${props => {
    if (props.primary) return "#03a9f3";
    if (props.danger) return "#f56342";
    return "transparent";
  }};
  font-weight: bold;
  margin-right: 20px;
  padding: 8px 16px;
  transition: all 0.2s ease-in-out;
  border-radius: 4px;
  border: 2px solid
    ${props => {
      if (props.primary) return "#03a9f3";
      if (props.danger) return "#f56342";
      return "#03a9f3";
    }};

  &:hover {
    color: ${props => (!props.primary && !props.danger ? "#0f7ae5" : "#ffffff")};
    background-color: ${props => {
      if (props.primary) return "#0f7ae5";
      if (props.danger) return "#be391c";
      return "transparent";
    }};
    text-decoration: none;
    border: 2px solid ${props => (props.danger ? "#be391c" : "#0f7ae5")}};
  }
`;

export default StyledLink;
import React from "react";
import StyledLink from "./StyledLink";

export default () => (
  <nav className="container">
    <StyledLink primary link="/">Home</StyledLink>
    <StyledLink danger link="/about">About</StyledLink>
    <StyledLink link="/portfolio">Portfolio</StyledLink>
  </nav>
);
styled-components: styled custom component, with some props

styled-components: styled custom component, with some props


By : user2556633
Date : March 29 2020, 07:55 AM
this will help I have a
component, which takes a size prop. I want to take a Header with a size prop, and additionally style it with styled-components. , You can do:
code :
const MyHeader = styled(Header)({ ... });
const MyHeader = styled(Header)`
  color: red;
`
const Temp = () => <Header size="huge" />;
const MyHeader = styled(Header)({ ... });
How to test styled Material-UI components wrapped in withStyles using react-testing-library?

How to test styled Material-UI components wrapped in withStyles using react-testing-library?


By : Rick
Date : March 29 2020, 07:55 AM
wish of those help First of all when you use render method of react-testing-library you don't need to worry about using withStyles or any wrapper because at the end it renders the component as it could be in the real dom so you can write your tests normally.
Then as far as I can see you are doing the same thing I did when I was starting with tests (it means you are going to become good at it ;). You are trying to mock an internal method and that is not the best approach to follow because what you need to do is to test the real method.
code :
import ... more cool things
import * as api from './api';

const Register = () => {
  const [name, setName] = useState('');
  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (name) {
      api.registerUser({ name });
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <TextField
        id='name'
        name='name'
        label='Name'
        fullWidth
        value={name}
        onChange={handleNameChange}
      />
      <Button data-testid='button' fullWidth type='submit' variant='contained'>
        Save
      </Button>
    </form>
  );
}
import * as api from '../api'

jest.mock('../api')

api.registerUser = jest.fn()
it('should not call api registerUser method', () => {
  const { getByTestId } = render(<Register />)
  fireEvent.click(getByTestId('button'))
  expect(api.registerUser).toHaveBeenCalledTimes(0)
})
it('should call api registerUser method', () => {
  const { getByLabelText, getByTestId } = render(<Register />)

  fireEvent.change(getByLabelText('Name'), { target: { value: 'Steve Jobs' }})

  fireEvent.click(getByTestId('button'))
  expect(api.registerUser).toHaveBeenCalledTimes(1)
})
Related Posts Related Posts :
  • Semantic UI React - populate dropdown with remote content
  • Toggling font awesome Icon using React
  • How to this setState to set a value from function?
  • TypeScript and React - children type?
  • How to use Redux with React
  • How can I remove the bar in the react-select?
  • How can I store a img into a MongoDB?
  • ReactJS: setState using if else
  • React skip API request if data already exists
  • Reused React element prevents component updates
  • how to change default index page to login page in react js
  • Why does my React app append the external URL to http://localhost:/<port> and not to ONLY the URL itself?
  • How do I create a dockerized development environment for ReactJS
  • implementing force update with react native apps
  • React: avoid rendering component's root DOM element if DOM children are empty
  • Enzyme: Value props returns undefined in simulating onChange event
  • How to do Refresh in React Native ScrollView with refreshControl?
  • createBottomTabNavigator keep stackes mounted
  • Why am I unable to access a Redux store in a child React component?
  • Possible to do a callback in setState like this in React?
  • use ownProps in mapDispatchToProp
  • How to style react-native-sectioned-multi-select?
  • Managing Multiple States React
  • How to set focus after React state update/render
  • What is difference between reactstrap and react-bootstrap?
  • detect the uniqueness of the usernames with Firebase and react js
  • How "history" object is getting evaluated in React
  • Why is React Router not changing views on URL change?
  • How to use DRACOLoader with GLTFLoader in ReactJs?
  • How do I return a json file from s3 to a specific url, but only that url
  • Loading spinner with react useEffect hook and Redux and without useState hook
  • Jest - Could not locate module with dynamic import template string
  • Reactjs class components not rendered but functions are rendered in IE11
  • can i use the tsx extension for test files if using react with typescript
  • Material-ui: Difference between Expansion Panels and Collapse
  • When should I use a this.context vs Consumer in the New Context API in React?
  • Dynamic Component with React Router
  • How to inherit vanilla option component in a custom option component in react-select v2?
  • Is there a way to see the query produced by ReactiveSearch
  • How to describe type scroll events?
  • How to correctly mock React Navigation's getParam method using Jest
  • What is the better way to update other state variable which is dependent on another state variable while re-rendering?
  • Value of state variable is lost - React
  • How to compress the files using gzip in react app
  • Can we redirect to in reduxSaga
  • TypeError: Cannot read property 'map' of undefined (jest.js)
  • How to get state data from child to parent component?
  • Switching SubRoutes without unmounting MainRoute (React-Router-Dom)
  • Value must be set for boolean attributes with Typescript and Material UI
  • React + Firebase using hooks?
  • How to pass className style to sub component in `material-ui`?
  • How to create React hooks that forward dependencies
  • How to deploy React (NextJS) project with docker?
  • How to refetchQueries a query having an args option
  • How to fix "404" error when directly accessing a component in react
  • Cannot read property of undefined when using react hooks
  • React - Display message while binding data
  • React show/hide content
  • should I use shouldComponentupdate?
  • How to define a custom class to HighchartsReact component
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk