Next.js Discord

Discord Forum

Access a certain variable in another file?

Unanswered
X posted this in #help-forum
Open in Discord
Avatar
XOP
Hello everyone, i want to know how to access a certain value cross-files.

For example, here, i want to access the value of color to use it in another file but i'm not too sure on how to go about it.
Image

74 Replies

Avatar
XOP
anyone please ?
Avatar
do you want it to be accessible in the whole app?
Avatar
XOP
no
i have another file, where the backgroundcolor is white
and another file where i can pick a color via a color picking module
Avatar
pass it as a prop to that component
Avatar
XOP
do you have an example ? because i already tried that and got messed up
Avatar
can u show me the other component
?
Avatar
XOP
yes of course
const container: React.CSSProperties = {
  backgroundColor: "white",
};





export const Main = ({ title }: z.infer<typeof CompositionProps>) => {



  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  const transitionStart = 2 * fps;
  const transitionDuration = 1 * fps;

  const logoOut = spring({
    fps,
    frame,
    config: {
      damping: 200,
    },
    durationInFrames: transitionDuration,
    delay: transitionStart,
  });



  const titleStyle: React.CSSProperties = useMemo(() => ({
    fontFamily: fontFamily,
    fontSize: 70,
    color: 'black',
    fontWeight: 'bold',
  }), [fontFamily]);




  return (
   
    <AbsoluteFill style={container}>
      <Sequence durationInFrames={transitionStart + transitionDuration}>
        <Rings outProgress={logoOut}></Rings>
        <AbsoluteFill style={logo}>
          <NextLogo outProgress={logoOut}></NextLogo>
        </AbsoluteFill>
      </Sequence>
      <Sequence from={transitionStart + transitionDuration / 2}>
        <TextFade>
          <h1 style={titleStyle}>{title}</h1>
        </TextFade>
      </Sequence>
    </AbsoluteFill>
  );

  
};
the white background in the beginning is what i want to change
export const RenderControlss: React.FC<{
  color: string;
  setColor: React.Dispatch<React.SetStateAction<string>>;
  inputPropss: z.infer<typeof CompositionProps>;
}> = ({ inputPropss }) => {
  const {  state, undo } = useRendering(COMP_NAME, inputPropss);


  const [color, setColor] = useState("#aabbcc");
  



  return (
    <div className={cn(
      "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
      
    )}>
      {state.status === "init" ||
      state.status === "invoking" ||
      state.status === "error" ? (
        <>


<FontPicker/>
      <DropdownMenu>
        <DropdownMenuTrigger>TitanOne </DropdownMenuTrigger>  
        <DropdownMenuContent>
          <DropdownMenuItem  >Montserrat</DropdownMenuItem>
          <DropdownMenuItem >Inter</DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      {/*<HexColorPicker color={color} onChange={setColor} />*/}

   etc.......................



this is the file where i pick my color
Avatar
use a global statemanagement library instead.
idk if there is a better way to do it.
but something like redux can work.
Avatar
XOP
is it hard to implement ?
Avatar
nope
not at all
Avatar
XOP
i also have another question but maybe its more module related
i went to the discord of the concerned module and they havent replied to my question
Avatar
sadly,i have no idea about that :/
Avatar
XOP
okay i opened redux docs and im very confused
Avatar
ig chatgpt can explain it better
like you just have to initialize the redux provider in your app.tsx file
Image
provider in your case
Avatar
XOP
app.tsx ? even tho i want to transfer a variable to another file and none of those files are app.tsx ???
Avatar
you are using app router or page ?
like do you have layout.tsx?
Avatar
XOP
page
Avatar
anyways
what redux does
Avatar
XOP
yes
Avatar
that it stores the state in a file that can be accessed by other files in the app
so for this you have to initialize it in your entrypoint file
Avatar
XOP
this is all complex for such a simple problem
access a variable in another file
Avatar
u can access variable of parent component to their childrens
Avatar
XOP
but then i'd have to change half my code, it's not as easy as you say it
it depends on the code structure of the project
Avatar
by this you can access the variable
Avatar
function func1() {
  let x = 1;
}

function func2() {
  // how to get x here???
}

it's not such a simple problem. the state color is bound to the component declaring that state and to send that color to a different function requires non-trivial changes
Avatar
wherever you want
Avatar
XOP
what do you mean by non-trivial changes
Avatar
i meant you can't expect to do that in one or two lines of code only. read the react tutorial and documentation on how to share states to another component.
Avatar
XOP
okay but how do i implement Redux?
Avatar
watch tutorials on redux
its not that complex
once you get it
and it solves many problems
Avatar
XOP
@Splash is it possible to save the state to url and access it ?
Avatar
what url?
Avatar
XOP
for example, since my color state is just a hex code, cant i make a url parameter ?color=#000000
Avatar
i hv no idea abt that
Avatar
XOP
okay
Avatar
i dint get what ur talking abt
just try redux
you wont regret
Avatar
XOP
im trying, the hard part is actually understand what's going on and what applies for my case + what doesn't.
it's not that i'm not willing
Avatar
global statemanagement is all you need
Avatar
yeah you can do that
'use client'
import { useSearchParams } from 'next/navigation'

...
const searchParams = useSearchParams()
const color = searchParams.get('color') || '#aabbcc'

const changeColor = (color) => {
  const params = new URLSearchParams(searchParams.toString())
  params.set('color', color)
  window.history.pushState(null, '', `?${params.toString()}`)
}

...
Avatar
XOP
would that be reliable though? any SEO problems ?
Avatar
it is changing the color on client side
Avatar
XOP
correct
does that update realtime ?
Avatar
what do you mean realtime?
Avatar
XOP
does it update constantly ?
Avatar
useSearchParams is a react hook, it does update the page when the value has changed
Avatar
XOP
great, i'll test that right now
thank you! that worked well.
only error i have now is:

Type 'string | null' is not assignable to type 'BackgroundColor | undefined'.
Avatar
const color = searchParams.get('color') || '#aabbcc'
Avatar
XOP
an exclamation mark fixes that.