Styled Components warning for dynamically imported React components - javascript

From a headless CMS I'm fetching the list of components which should be included on certain page. Once fetched, I dynamically import mentioned components like this:
const components = ["Test", "Test2"]; // comes from CMS
const DynamicComponent = ({ name }) => {
let Component;
Component = require(`./components/${name}`).default;
return <Component />;
};
export default function App() {
return (
<Container>
{components.map((comp, i) => (
<DynamicComponent name={comp} key={i} />
))}
</Container>
);
}
And then I just pass these component as children props to some container.
However, although everything works fine, I'm getting some warning for every component I have that says:
The component styled.div with the id of "sc-bdnylx" has been created dynamically.
You may see this warning because you've called styled inside another component.
To resolve this only create new StyledComponents outside of any render method and function component.
I googled the warning but everywhere the solution is to not define styles within the component. I could be wrong, but I don't think that's applicable here.
Here's the full example: https://codesandbox.io/s/style-components-dynamic-5id3y?file=/src/App.js (check the console output)
How can I get rid of this warning?
Thank you

Well, the warning is pretty clear when it says "create new StyledComponents outside of any render method and function component". So what you can do is refactor your functional component DynamicComponent into a class based component
class DynamicComponent extends React.Component {
constructor(props) {
super(props);
this.Component = require(`./components/${this.props.name}`).default;
}
render() {
return <this.Component />;
}
};
EDIT: tested on your sandbox, made the fixes to my previous code, and your warnings are gone

Related

Why aren't my props available to use in my component when I need them?

I keep running into similar issues like this, so I must not fully understand the lifecycle of React. I've read a lot about it, but still, can't quite figure out the workflow in my own examples.
I am trying to use props in a child component, but when I reference them using this.props.item, I get an issue that the props are undefined. However, if the app loads and then I use the React Browser tools, I can see that my component did in fact get the props.
I've tried using componentDidMount and shouldComponentUpdate in order to receive the props, but I still can't seem to use props. It always just says undefined.
Is there something I'm missing in React that will allow me to better use props/state in child components? Here's my code to better illustrate the issue:
class Dashboard extends Component {
state = { reviews: [] }
componentDidMount () {
let url = 'example.com'
axios.get(url)
.then(res => {
this.setState({reviews: res.data })
})
}
render() {
return(
<div>
<TopReviews reviews={this.state.reviews} />
</div>
);
}
}
export default Dashboard;
And then my TopReviews component:
class TopReviews extends Component {
state = { sortedReviews: []}
componentDidMount = () => {
if (this.props.reviews.length > 0) {
this.sortArr(this.props.reviews)
} else {
return <Loader />
}
}
sortArr = (reviews) => {
let sortedReviews = reviews.sort(function(a,b){return b-a});
this.setState({sortedReviews})
}
render() {
return (
<div>
{console.log(this.state.sortedReviews)}
</div>
);
}
}
export default TopReviews;
I'm wanting my console.log to output the sortedReviews state, but it can never actually setState because props are undefined at that point in my code. However, props are there after everything loads.
Obviously I'm new to React, so any guidance is appreciated. Thanks!
React renders your component multiple times. So you probably see an error when it is rendered first and the props aren't filled yet. Then it re-renders once they are there.
The easy fix for this would be to conditionally render the content, like
<div>
{ this.props.something ? { this.props.something} : null }
</div>
I would also try and avoid tapping into the react lifecycle callbacks. You can always sort before render, like <div>{this.props.something ? sort(this.props.something) : null}</div>
componentDidMount is also very early, try componentDidUpdate. But even there, make your that your props are present.
For reference: see react's component documentation

React context props drilling, what is it that I don't get?

There is a TL;DR at the bottom.
I am probably doing this wrong or using the context in an bad way. I am new to react so I have no clue if this is how we are meant to do things.
My understanding:
Context can be used to pass down props to deeper nested child components without having to pass them through all levels of nesting. A provider is filled with props, and a consumer will look "up the tree" to find the nearest provider and get it's data.
If this is the case, then I can load a provider with a function, such as an onChange handler in order to avoid having to write the handler on every child component when they all do the same thing. This would allow for a "smart form" which govern's its input's handlers by "passing" handlers given to it. Obviously just writing one handler on multiple components is not an issue, but having like 20-30 form fields and writing 4+ handlers on each of them just creates code clutter. So I tried the following:
HTML structure is like this, for example:
<ControlledForm data={some_data} handlers={some_handlers}>
<LabeledControl name="Type your name" rel="Name" meta={{some_meta_object}}></LabeledControl>
<LabeledControl name="Pet name" rel="PetName" meta={{some_meta_object}}></LabeledControl>
<LabeledControl name="Type of pet" rel="PetType" meta={{some_meta_object}}></LabeledControl>
<LabeledControl name="Family" rel="Family" meta={{some_meta_object}}></LabeledControl>
</ControlledForm>
And this is the ControlledForm class code:
const { Provider } = React.createContext(); //Note this
class ControlledForm extends Component {
state = {};
render() {
return (
<Provider value={{ onChange: this.props.onChange }}>
<form>{this.props.children}</form>
</Provider>
);
}
}
Now whatever child I place within this form would want to have a <Consumer> wrapper around it to consume the changeHandler, or at least this is the plan. However when I wrap my LabeledControl in a consumer, it acts as if it has no data.
<LabeledControl> (reduced code):
const { Consumer } = React.createContext();
class LabeledControl extends Component {
state = {};
render() {
return (
<Consumer>
{r => {
console.log("consumer:", r); //Logs undefined
return (
<div className="labeled-control">
{/*Code here*/}
</div>
);
}}
</Consumer>
);
}
}
If I was to guess at what the issue is, I'd say it is because both the ControlledForm and the LabeledControl create it's own context, which is not shared, look at the code above. But I do not understand how would I share this context and still keep the two classes in separate .js files. I cannot pass a reference down to the children, all I get is the {this.props.children} and no way to tell it "Hey use this provider here". All the examples I find online have the two classes that are a provider and a consumer in a same file, being able to reference the same "context" but this seriously impacts the freedom of what I can put inside a form, or rather doesn't let me have customization in terms of "children".
TLDR
How do I pass down a "Context" from a Provider to a Consumer when they are in two different javascript files? Code is above. I essentially need to pass down a handler to every child and have it (maybe, maybe not, depending on a child) use the handler to tell the parent to update it's data. All of this whilst using {this.props.children} in a parent in order to allow "outter code" to "inject" the parent component with any children desired and have them either use or not use the parent's handler.
Edit:
I searched about a bit and found two possible solutions, which I both tested and both seem to be working (with a limited use case). Both render props and React.CloneElement seem to do the trick when there is one level of nesting as we can directly render and add props to children with them, but when we need to prop drill several levels, all the components in between would have to implement the same passing of props which then turns to spaghetti code. Still searching to try and find the way to pass the context down to the children for consumption in different files.
Please view the code below.
Also: here is a sample project I have built:https://codesandbox.io/s/5z62q8qnox
import React from 'react'
import PropTypes from 'prop-types';
import 'bootstrap/dist/css/bootstrap.min.css';
export default class ControllerForm extends React.Component {
static childContextTypes = {
onChange: PropTypes.func.isRequired
}
getChildContext() {
return {
onChange: this.handleOnChange
}
}
handleOnChange = (e) => {
console.log(e.target.value) //here is the place you have to implement
}
render() {
return (
<div class="container">
{this.props.children}
</div>
)
}
}
import React from 'react'
import PropTypes from 'prop-types';
import 'bootstrap/dist/css/bootstrap.min.css';
export default class LabeledControl extends React.Component {
static contextTypes ={
onChange : PropTypes.func.isRequired
}
render() {
return (
<div>
<div className="form-group">
<input className="form-control" type="text" onChange={this.context.onChange} />
</div>
</div>
)
}
}
function App() {
return (
<div className="App">
<ControllerForm>
<LabeledControl />
<LabeledControl />
</ControllerForm>
</div>
);
}
It appears that Context is not what I should be using for this, instead either render props or React.cloneElement() is the proper solution, despite my best efforts to enforce a context.
Parent's render:
{this.props.children.map((child, index) =>
React.cloneElement(child, { key: index, handler: handler })
)}
Child's render:
return (
<div>
<span onClick={this.props.handler}>{passed.foo}</span>
</div>
);
This way the structure remains clean and handlers get passed down. Only issue is every component that needs to pass them down has to implement this, but it would have been the same with context, since it is not exported to a separate file.

React onClick event handler not working using Next.js

I'm making a Reddit clone and I'm using Next.js so its server-side rendered. I started without using Next.js and when I learned about it, I immediately switched to it.
I've created a custom _app.js so the header and sidebar exist on every page, and for it to act as the topmost component to hold application state. The later isn't quite working out.
Here's .project/src/pages/_app.js:
import App, { Container } from 'next/app';
// Components
import Header from '../components/Header/Header';
const MainLayout = props => (
<React.Fragment>
<Header
isSidebarOpen={props.isSidebarOpen}
sidebarToggle={props.sidebarToggle}
/>
{props.children}
</React.Fragment>
);
export default class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps };
}
state = {
isSidebarOpen: true
};
sidebarToggle = () => {
this.setState({ isSidebarOpen: !this.state.isSidebarOpen });
};
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<MainLayout
isSidebarOpen={this.state.isSidebarOpen}
sidebarToggle={this.sidebarToggle}
>
<Component {...pageProps} />
</MainLayout>
</Container>
);
}
}
The issue I'm having is, isSidebarOpen and sidebarToggle are being passed to exactly where I need them – they show up in the console – but the onClick handler doesn't activate and if I change isSidebarOpen, it doesn't take effect until I restart the server. I used this approach before using Next.js and it worked as expected.
How can I achieve what I'm trying to do? I've read the docs, searched Google and Stack Overflow. I even checked issues on their repo without luck. I suspect it to be something to do with a custom _app.js, as the props are passed down correctly.
One possibility might be to define your sidebarToggle function within the component you are using.(Maybe because calling it inside Component the code might be running in _app.js instead of your component this is a big maybe! but worth a try)
Here _app.js is a wrapper around your application and I don't think it is suited to be used at the topmost component to hold state. Better to make a simple react root Component do that!

React Render with Hoc

So I am following some tutorial and I am confused regarding how things render when using HOC
So firstly, I guess props flow from parent to child and is one directional?
Here we created two HOC, The Aux and withclass
The Aux doesn't do anything special besides passing props.children
const aux = (props) => props.children;
export default aux;
The withClass HOC function takes two parameter App and className..
const withClass = (WrappedComponent, className) => {
return class extends Component {
render () {
return (
<div className={className}>
<WrappedComponent {...this.props} />
</div>
)
}
}
And our App.js which is passed as an argument looks like this
import React, { PureComponent } from 'react';
import classes from './App.css';
import Persons from '../components/Persons/Persons';
import Cockpit from '../components/Cockpit/Cockpit';
import Aux from '../hoc/Aux';
import withClass from '../hoc/withClass';
class App extends PureComponent {
//something
render () {
if ( this.state.showPersons ) {
persons = <Persons
persons={this.state.persons}
clicked={this.deletePersonHandler}
changed={this.nameChangedHandler} />;
}
return (
<Aux>
<button onClick={() => { this.setState( { showPersons: true } ) }}>Show Persons</button>
<Cockpit
appTitle={this.props.title}
showPersons={this.state.showPersons}
persons={this.state.persons}
clicked={this.togglePersonsHandler} />
{persons}
</Aux>
);
}
}
export default withClass( App, classes.App );
[Question] So based on the above code if someone can please explain what exactly happens, the way things execute and render?
Secondly, We used {...this.props} in our withClass HOC because according to the instructor they are wrapped and hence our other component, even though they receive prop they can't pass them. Can someone explain this with an example? Also {...this.props} creates copy of all the props? and shouldn't it be like <WrappedComponent = {...this.props} /> instead of <WrappedComponent {...this.props} />
First of all, what is a HOC?
A HOC is a Higher-order component. This means it is a function that takes as its first argument a component and then returns a component.
From this definition you can immediately see that:
withClass is an HOC
Aux is not an HOC
Aux is a functional component. Classic React components are created by defining a class that inherits from React.Component. A newer, simpler way of defining components is to create functions that simply accept props as the first parameter and return what should be rendered.
So based on the above code if someone can please explain what exactly happens, the way things execute and render?
Well, let's look at App just as a component. We have withClass and App and you're exporting withClass(App, classes.App). What would it look like if, instead of using an HOC we used a functional component? It'd look like this:
const AppWithClass = props =>
<div className={classes.App}>
<App/>
</div>
In this case, no props are passed to App. So with this use-case, there is no need to pass props through by writing {...props}. And you'd then simply export AppWithClass.
But usually you write HOCs to be reusable. In that case, you don't know if the component that will be passed to your HOC will receive props or not. For that reason, you want the component you create to take any props passed to it and to pass them through to the wrapped component.
Let's say you have a Button component that takes a parameter colour. You'd typically use it like this:
<Button colour="red"/>
But you want to wrap it with a div and add a class to that div. So you use withClass as follows:
const ButtonWithClass = withClass(Button, "button-class");
Now you can use Button as follows:
<ButtonWithClass colour="red"/>
And really what you'll get is:
<div className="button-class">
<Button colour="red"/>
</div>
If you did not write {...this.props} when rendering WrappedComponent in your withClass HOC, then colour would not get passed through to Button. In your HOC, WrappedComponent is equal to Button in the above case.
The syntax {...this.props} is a combination of the Object literal spread syntax and JSX's own behaviour. The Object spread syntax used in this way means the keys of the given object will become the prop names and the values will become their respective values. So when you write {...{ colour: 'red' }} you're asking JSX to get props from an object that you define inline.
To continue with the above example:
<ButtonWithClass colour="red"/>
Inside withClass this becomes equivalent to:
const WrappedComponent = Button;
return <WrappedComponent {...this.props}/>;
And here this.props equals { colour: 'red' }. So the above becomes:
const WrappedComponent = Button;
return <WrappedComponent {...{ colour: 'red' }}/>;
Which then becomes:
const WrappedComponent = Button;
return <WrappedComponent colour="red"/>;
I hope that helps!

Integrating and rendering react-swipe-cards

I am very noob with reactJs, in fact I just finished this course and am struggling with some concepts here.
I am willing to create an app for people to express their preferences with regards of subjects for a newsletter, and have grabbed a very comprehensive list of topics (2k+) and wanna make some fun way to select them, so I think that something along the lines of Tinder swipeable cards would be a perfect fit, so I am trying to implement this react module functionality into my App.
But it is not showing up anything.
I just created a Repo, in which I had a few tries with no luck.
Basically, the example provided in the module documentation says that it should start by
const data = ['Alexandre', 'Thomas', 'Lucien', 'Raphael', 'Donatello', 'Michelangelo', 'Leonardo']
const Wrapper = () => {
return (
<Cards onEnd={console.log("action('end')")} className='master-root'>
{data.map(item =>
<Card
onSwipeLeft={console.log("action('swipe left')")}
onSwipeRight={console.log("action('swipe right')")}>
<h2>{item}</h2>
</Card>
)}
</Cards>
)
}
But I am completely lost with it, I supposed that it should provide me with a React Component <Something />, but instead it generate something in the lines of a function, that returns a div, which looks a lot with a component, but I have no idea about how integrate into this example.
Note: In the repo graph, I noticed that there is another developer that made some adjustments to make it compatible with react 16.xx.beta, I'v tried it also, no lucky also.
I am almost sure, that there are some concepts I am missing here, so, any reference is more than welcome, also.
What you are looking for is a functional stateless component, the below code
const Wrapper = () => {
return (
<Cards onEnd={console.log("action('end')")} className='master-root'>
{data.map(item =>
<Card
key={item}
onSwipeLeft={() => {console.log("action('swipe left')")}}
onSwipeRight={() => {console.log("action('swipe right')")}}>
<h2>{item}</h2>
</Card>
)}
</Cards>
)
}
is a functional component.
According to documentation
Functional and Class Components
The simplest way to define a component is to write a JavaScript
function:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
This function is a valid React component because it accepts a single
“props” (which stands for properties) object argument with data and
returns a React element. We call such components “functional” because
they are literally JavaScript functions.
The way to render a function component is just like you would render a normal React component
<Wrapper {...props} /> // {...props} is a spread operator syntax to just pass all the props down to wrapper you can pass selected props too
Also react-swipe-card doesn't provide you Wrapper functional component, it provides you components like Cards and Card which you used to render the card view in the Wrapper Component
import Cards, { Card } from 'react-swipe-card'
Now in your case it would look like
export default class MyCards extends Component {
render() {
return <Wrapper />;
}
}
However since you don't have a state and also you are not using lifecycle functions you could simple write the above MyCards Component as
export const MyCards= () => {
return <Wrapper />;
}
I however assume that you would eventually be writing some of the logic there and hence keep it a stateful React component. I have also include the logic whereby you would handle the state change on left or write swipe.
Check a working DEMO
P.S. I a recommendation to go through the React docs thoroughly as they have explained the concepts really well
If I understand you question as suppose. It look you have some small mistake. I download the repo and run you test on React 15.4.2
Your Card component call:
<Card
onSwipeLeft={console.log("action('swipe left')")}
onSwipeRight={console.log("action('swipe right')")}>
<h2>{item}</h2>
</Card>
My Card component call:
<Card
key={item}
onSwipeLeft={()=>{console.log("action('swipe left')")}}
onSwipeRight={() => {console.log("action('swipe right')")}}>
<h2>{item}</h2>
</Card>
We need to create scope for events handler that is why one of the solution is a arrow function. They aren’t just syntactic sugar around anonymous functions though. An arrow function does not have its own context and will instead use the same this as the context in which it was defined. Here is more detail handle-events-in-react-with-arrow-functions
Also on the MyCards you are returning something like (your code)
export default class MyCards extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return Wrapper;
// return (
// <div>
// <p>Something</p>
// {Wrapper();}
// </div>
// );
}
}
But you should return a component and the way is return it have to be
export default class MyCards extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return <Wrapper/>
}
}
Suggestion: If you are not going to have any state in the MyCards component you can make it a functional Component
The current top answer is correct and great about the concept of the functional component. You are actually creating a High Order Component.
However I feel your repo can actually be fixed by just making this change:
render() {
return Wrapper();
}
See that I actually executed the Wrapper function in order to get the Component as a result, otherwise you are rendering a function and not a Component.
You can refactor your code to actually extend a React.Component, and I actually recommend this as HOC are better used for another type of objective, like decorators.
See here, the only thing I changed is that: https://codesandbox.io/s/xp6pzpyoq

Categories

Resources